這個程序應該輸入someones名稱並輸出它像「Last,first middle」。名字應該被存儲在3個不同的數組中,並且它們是最後一個全名的第四個數組。我也應該使用strncpy和strncat來構建第四個數組。我遇到的問題是我不知道在這種情況下使用strncpy會怎樣,以及如何使用它。我可以讓程序說「最後一箇中間」,但不是正確的輸出。已經是while循環應該是另一個問題IM允許用戶說「Q」或「Q」和退出程序,但它沒有做到這一點C++ c-string,strncat,strncpy
#include <iomanip>
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char replay; //To hold Q for quit
const int SIZE = 51;
char firstName[SIZE]; // To hole first name
char middleName[SIZE]; // To hold middle name
char lastName[SIZE]; // To hold last name
char fullName[SIZE]; //To hold the full name
int count = 0;
int maxChars1;
int maxChars2;
cout << "Enter Q to quit or enter your first name of no more than " << (SIZE - 1)
<< " letters: ";
cin.getline(firstName, SIZE);
while(firstName[SIZE] != 'Q' || firstName[SIZE] != 'q')
{
cout << "\nEnter your middle name of no more than " << (SIZE - 1)
<< " letters: ";
cin.getline(middleName, SIZE);
cout << "\nEnter your last name of no more than " << (SIZE - 1)
<< " letters: ";
cin.getline(lastName, SIZE);
maxChars1 = sizeof(firstName) - (strlen(firstName) + 1);
strncat(firstName, middleName, maxChars1);
cout << firstName << endl;
maxChars2 = sizeof(lastName) - 1;
strncpy(firstName, lastName, maxChars2);
lastName[maxChars2] = '\0';
cout << lastName << endl;
}
system("pause");
return 0;
}
如果使用C++,不要使用char *而使用std :: string。如果C,不要使用'std :: cin',而是使用'fgets()'。 – 2013-04-23 16:21:01
提示:您的代碼應該將結果彙編到'fullName'中。這可能應該被定義爲足夠大以容納所有三個組件,但是如果它足夠大,那麼使用'strn'函數就沒有意義了,所以你不會學習這個練習應該教給你的東西。 – 2013-04-23 16:28:37
@Steve Jessop但是爲什麼我會在這裏使用strncpy或strcpy? – user1807815 2013-04-23 16:50:06