我正在为这个任务上课,我遇到了一个问题。操纵字符串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',因为你已经将它用于你的函数参数了? –