我正在爲這個任務上課,我遇到了一個問題。操縱字符串C++
該計劃的目標是讓用戶
- 輸入他們的第一個,然後姓氏。
- 然後程序會要求輸入一個暱稱。
最後程序將輸出您
- 名字
- 暱稱引號全部大寫
- 姓氏
的說明更詳細的版本可以找到here
所以我的問題在於我將如何處理一個字符串以將暱稱放在第一個和最後一個之間。
我使用cin.getline()
在開頭輸入名和姓。 我似乎無法找到字符串中的姓氏。有沒有辦法在數組中的某個位置之後將字符串/ char []讀入另一個字符串中。
一樣,如果有一些C++本地庫的函數去(僞代碼)
readFromPoint(array, otherArray, beginPoint, stopPoint);
還是我只是將不得不建立自己的循環。
我想輸入我的名字和姓氏到一個字符串中。然後將它們放入兩個單獨的字符串。然後,我將(首先,暱稱,最後一個)放入第一個和原始字符串中。
我知道如果我只用了兩個cin語句,它可以爲我節省很多心痛。 (我相信我已經聽到別人稱呼它是危險的)
這裏是我的代碼:
#include <iostream>
#include <cstring>
using namespace std;
char Name[46], // the full names leangth - 2
firstName[16],
lastName[16],
nickName[16];
int numOSpaces;
//void rearrangeName();
int FindSpace(string, int);
int FindNull(string);
int main(){
cout << "Pleast enter your first then last name...\n";
cin.getline(Name, 30);
int ender = FindSpace(Name, strlen(Name));
// here we check if you entered the right amount of spaces
while (numOSpaces > 1 || numOSpaces < 1){
if (numOSpaces > 1)
cout << "There are too many spaces only put one space:\n";
if (numOSpaces < 1)
cout << "Please separate your first and last name:\n";
cin.getline(Name, 30);
ender = FindSpace(Name, strlen(Name));
}
cout << "Hello " << Name <<".\n";
cout << "\n\nEnter your nickname...\n";\
cin.getline(nickName, 30);
cout << "Whats up " <<nickName << "!" << endl << endl;
// Now we separate the first name and the last name
//rearrangeName();
}
// used to tell where user stopped inputting into the string
int FindNull(string find){
int index = 0;
do{
index++;
}while (isprint(find[index])); // this stops at the null terminator
// }while (find[index] != '\0'); // as will this
return index;
}
// here we find the first space
int FindSpace(string mystring, int size){
int Space;
int spaceCount = 0;
for (int index; index < size; index++){
if (isspace(mystring[index])){
Space = index;
spaceCount++;
}
}
numOSpaces = spaceCount;
return Space;
}
void findName(string fullName, string otherName){
}
如果我想那就是把這個我不能使用過程中的任何外部庫。只有那些C++原生的。
使用'的std :: string'這是C++標準庫的一部分,然後這一切都變得容易。在C++中使用原始字符數組是一個可怕的想法。 –
'cin'很危險? –
'char Name [46]'等。你爲什麼不爲這些使用'std :: string',因爲你已經將它用於你的函數參數了? –