我需要以下程序来获取整行用户输入并将其放入字符串名称:
cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
getline(cin, names);
Run Code Online (Sandbox Code Playgroud)
然而,使用cin >> number命令之前的getline()命令(我猜这是问题),它不允许我输入名称.为什么?
我听说过一个关于cin.clear()命令的事情,但我不知道这是如何工作的,或者为什么这甚至是必要的.
在C++入门书中,在第(1)章中,它提到了以下内容:
endl是一个特殊的值,称为操纵器,当写入输出流时,具有向输出写入换行符并 释放与该设备关联的缓冲区的效果.通过浏览缓冲区,我们确保用户将立即看到写入流的输出.
在这里"冲洗缓冲区"是什么意思?
是否有一个原因,如果在我的程序中我要求用户输入,我这样做:
int number;
string str;
int accountNumber;
cout << "Enter number:";
cin >> number;
cout << "Enter name:";
getline(cin, str);
cout << "Enter account number:";
cin >> accountNumber;
Run Code Online (Sandbox Code Playgroud)
为什么在输入第一个数字后,它输出"输入名称",然后立即输入"输入账号",然后我甚至输入我的"str"为getline(cin,str)线?谢谢!
我正在尝试在一个字符串变量中收集用户的输入,该变量在指定的时间内接受空格.
由于通常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)
任何的想法?