如何将给定的字行输入到以space分隔的不同字符串中?
How to input the given word line into different strings seperated by space?
我是 c++ 的新手,发现它很难使用 strings.User 正在输入他的全名,即名字和姓氏由 space 和 分隔,我想将它存储在不同的地方他输入名字时的字符串
输入
ABC XYZ
代码
string s1,s2;
getline(cin,s1);
getline(cin,s2);
cout<<"Firstname :"<<s1<<endl;
cout<<"Lastname :"<<s2<<endl;
输出
Firstname :ABC XYZ
Lastname : //nothing is printed here , i want to sore the last name here
做:
cin >> s1 >> s2;
cout<<"Firstname :" << s1 <<endl;
cout<<"Lastname :" << s2 <<endl;
或
string s1,s2;
getline(cin,s1);
auto pos = s1.find(' ');
s2 = s1.substr(pos);
s1 = s1.substr(0, pos);
cout<<"Firstname :" << s1 << endl;
cout<<"Lastname :" << s2 << endl;
那是因为 std::getline
直到看到 \n
才会停止,您可以提供自己的分隔符:
string s1,s2;
getline(cin,s1, ' '); // stop at whitespace
getline(cin,s2); // stop at \n
旁注:在这个小程序中它很好,但是当你进入更大的程序时,你会想要避免使用 using namespace std;
.
我是 c++ 的新手,发现它很难使用 strings.User 正在输入他的全名,即名字和姓氏由 space 和 分隔,我想将它存储在不同的地方他输入名字时的字符串
输入
ABC XYZ
代码
string s1,s2;
getline(cin,s1);
getline(cin,s2);
cout<<"Firstname :"<<s1<<endl;
cout<<"Lastname :"<<s2<<endl;
输出
Firstname :ABC XYZ
Lastname : //nothing is printed here , i want to sore the last name here
做:
cin >> s1 >> s2;
cout<<"Firstname :" << s1 <<endl;
cout<<"Lastname :" << s2 <<endl;
或
string s1,s2;
getline(cin,s1);
auto pos = s1.find(' ');
s2 = s1.substr(pos);
s1 = s1.substr(0, pos);
cout<<"Firstname :" << s1 << endl;
cout<<"Lastname :" << s2 << endl;
那是因为 std::getline
直到看到 \n
才会停止,您可以提供自己的分隔符:
string s1,s2;
getline(cin,s1, ' '); // stop at whitespace
getline(cin,s2); // stop at \n
旁注:在这个小程序中它很好,但是当你进入更大的程序时,你会想要避免使用 using namespace std;
.