引言:
C++提供了强大的string类型,但是其输入的时候还是要注意以下细节。
如果我们输入了一句话,里面包含有空格,str会被截断,空格后面的将不被保留。
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str;
cin >> str;
cout << str << endl;
return 0;
}
那么我们将如何保留空格输出呢?
一、使用getline
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
string str;
getline(cin,str);
cout << str << endl;
return 0;
}
二、使用字符用于判断
#include <iostream>
#include <queue>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
char c;
string str;
while ((c=cin.get()) != '\n')
{
str += c;
}
cout << str << endl;
return 0;
}