我正在尝试在一个字符串变量中收集用户的输入,该变量在指定的时间内接受空格.
由于通常cin >> str不接受空格,所以我将使用<string>中的std :: getline
这是我的代码:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
{
string local;
getline(cin, local); // This simply does not work. Just skipped without a reason.
//............................
}
//............................
return 0;
}
Run Code Online (Sandbox Code Playgroud)
任何的想法?
GMa*_*ckG 12
如果您输出存储的内容local(这是一个糟糕的变量名称,顺便说一下:P),您可以看到为什么会失败:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
{
string local;
getline(cin, local);
std::cout << "> " << local << std::endl;
}
//............................
return 0;
}
Run Code Online (Sandbox Code Playgroud)
>输入您的号码后,您会看到它会立即打印换行符.然后继续输入其余部分.
这是因为getline输入您的号码时会留下遗留下来的空行.(它读取数字,但显然没有删除\n,所以你留下一个空行.)你需要先删除任何剩余的空格:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n;
cin >> n;
cin >> ws; // stream out any whitespace
for(int i = 0; i < n; i++)
{
string local;
getline(cin, local);
std::cout << "> " << local << std::endl;
}
//............................
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是按预期工作的.
关于主题,也许只是针对手头的代码片段,但如果你没有,代码往往更具可读性using namespace std;.它违背了名称空间的目的.我怀疑这只是为了张贴在这里.
小智 6
输入数字后,声明一个字符以进入回车符。char ws;int n;cin>>n;ws=cin.get();
这将解决问题。
使用
cin>>ws而不是ws=cin.get(),将使您的字符串的第一个字符处于可变状态ws,而不仅仅是清除'\n'。