2016-02-01 2 views
1

В моем коде я пытаюсь добавить две строки вместе, однако по какой-то причине я не могу получить правильный тип возвращаемого значения для моей функции stringAdd. Я хочу вернуть c-строку. И моя реализация тоже не работает. Какие-либо предложения?добавление двух c-строк в C++

#include <iostream> 
#include<cstring> 

using namespace std; 
int stringLength(char *); // Function prototype 
char stringAdd(char *strPtr, char *strPtr2);//Function prototype 

int main() 
{ 
    const int SIZE = 51; // Array size 
    char letter; // The character to count 
    char word1[SIZE] = "Happy "; 
    char word2[SIZE] = "Birthday"; 

    cout <<"Your first c-string is: "<<word1<<"Your second c-string is: "<<word2<<"\n"; 
    cout << "The length of your first c-string is: "; 

    cout << stringLength(word1) << " chars long.\n"; 
    cout << "The length of your second c-string is: "; 

    cout << stringLength(word2) << " chars long.\n"; 

    if (SIZE >= (stringLength(word1) + stringLength(word2) + 1)) 
    { 
     cout << "we are gunna add ur strings"; 
     stringAdd(word1, word2); 
    } 
    else 
    { 
     cout << "String1 is not large enough for both strings.\n"; 
    } 
    return 0; 
} 

int stringLength(char *strPtr) 
{ 
    int times = 0; // Number of times a char appears in the string 

    // Step through the string each char. 
    while (*strPtr != '\0') 
    { 
     if (*strPtr != '0') // If the current character doesnt equals the null terminator... 
      times++; // Increments the counter 
     strPtr++; // Goes to the next char in the string. 
    } 
    return times; 
} 

Вплоть до этого момента мой код работает нормально, однако нижеследующая функция не работает вообще. Я не знаю, как я могу добавить два с-строку с использованием опорного

char stringAdd(char *strPtr, char *strPtr2) 
{ 
    int size1; 
    int size2; 
    size1= stringLength(strPtr); 
    int j=size1+1; // counter set to the num of chars in the first c-string 
    int i = 0; // counter for to add to the 2nd c-string 
    size2= stringLength(strPtr2); 
    size1=+size2; 
    char newWord[size1]; 

    for(int i=0;i<size1;i++) 
     newWord[i] = *strPtr[i] 
    for(int j=0;j<size2;j++) 
     newWord[i]= *str 
} 
+2

в вашем внутреннем 'если (* StrPtr = '0'!)', Вы забыли, спасаясь от '0' - вы, вероятно, имел в виду ' '\ 0' '. – mindriot

ответ

0

у вас есть опечатка в stringAdd, который вызывает ошибку

size1=+size2; 

Это должно быть

size1 += size2; 

В противном случае вы просто переписываете size1 со значением size2. Это, как говорится, в C++ вы не можете сделать это либо

char newWord[size1]; 

Размер массива должен быть известен во время компиляции не время выполнения.

0

Неверная функция stringAdd, поскольку она ничего не возвращает.

Кроме этого, если оператор в функции stringLength

if (*strPtr != '0') // If the current character doesnt equals the null terminator... 

    times++; // Increments the counter 

ПЭЭА не делают большой смысл, потому что условие в ограждающих в то время как заявление

while (*strPtr != '\0') 

такая же, как и в, если заявление.

{

функции можно записать следующим образом

size_t stringLength(const char *strPtr) 
{ 
    size_t n = 0; 

    while (strPtr[n]) ++n; 

    return n; 
} 


char * stringAdd(char *strPtr, const char *strPtr2) 
{ 
    char *p = strPtr + stringLength(strPtr); 

    while (*p++ = *strPtr2++); 

    return strPtr; 
} 

И в основной вы могли бы написать

if (SIZE >= (stringLength(word1) + stringLength(word2) + 1)) { 
    cout << "we are gunna add ur strings" << endl; 
    cout << stringAdd(word1, word2) << endl; 
} 
//... 

В этом случае word2 будет приложен к word1.

3

Во-первых, используйте std::string.

Затем, используйте std::string.

Наконец, если вы действительно должны манипулировать char массивы вручную, то по крайней мере использовать функции стандартной библиотеки C поэтому у вас есть надежда на получение нуль-терминации право. Функция, которую вы ищете, - std::strcat, которая объединяет две строки.

После этого используйте std::string.

0

Вы отметили это как «C++» и «c-strings», что вроде как просить автомобиль, который питается от мощности ног.

У вас есть 2 варианта:

  1. Используйте C строки ++
  2. Использование C струнные

Для первого:

#include <iostream> 
#include <string> 

int main() 
{ 
    std::string word1 = "Happy"; 
    std::string word2 = "Birthday"; 
    // ... your other stuff 
    std::string result = word1 + " " + word2 + "!"; 
    std::cout << "Result is " << result << std::endl; 
    return 0; 
} 

Для последнего:

#include <iostream> // if you are stuck using c-strings, this is kind of odd 
#include <cstring> 
#include <memory> 

int main() 
{ 
    const char* word1 = "Happy"; 
    const char* word2 = "Birthday"; 
    const unsigned int newWordSize = 20; // you only need 16 for this, so 20 is sufficient 
    char newWord[newWordSize]; 
    std::memset(newWord, newWordSize, 0); 
    std::strcpy(newWord, word1); 
    std::strcat(newWord, " "); 
    std::strcat(newWord, word2); 
    std::strcat(newWord, "!"); 
    std::cout << "New Word is " << newWord << std::endl; 
    return 0; 
} 

Почему то, что вы делаете неправильно:

// NOTE: If your null-terminators are not set, this breaks as it is an infinite loop. 
int stringLength(char *strPtr) 
{ 
    // NOTE: pointer arithmetic can speed up this function, and make this variable unnecessary 
    int times = 0; // Number of times a char appears in the string 

    // Step through the string each char. 
    while (*strPtr != '\0') 
    { 
     if (*strPtr != '0') // If the current character doesnt equals the null terminator... 
      times++; // Increments the counter 
     strPtr++; // Goes to the next char in the string. 
    } 
    return times; 
} 

char stringAdd(char *strPtr, char *strPtr2) // ERROR: your return value should probably be char*, and you will need to free that memory later 
{ 
    int size1; 
    int size2; 
    size1= stringLength(strPtr); 
    int j=size1+1; // counter set to the num of chars in the first c-string 
    int i = 0; // counter for to add to the 2nd c-string 
    size2= stringLength(strPtr2); 
    size1=+size2; 
    char newWord[size1]; // ERROR: you cannot allocate a dynamic array this way. 

    for(int i=0;i<size1;i++) // ERROR: you've set size1 = size1 + size2 + 1, and you attempt to access the first word with this new size. You will access memory outside the bounds of your array 
     newWord[i] = *strPtr[i] 
    for(int j=0;j<size2;j++) 
     newWord[i]= *str 
    // ERROR: You do not set the null-terminator for the new string 
    // ERROR: you do not return anything 
} 
Смежные вопросы