Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在cin之后使用getline(cin,s)_C++_Getline_Cin - Fatal编程技术网

C++ 在cin之后使用getline(cin,s)

C++ 在cin之后使用getline(cin,s),c++,getline,cin,C++,Getline,Cin,我需要以下程序获取整行用户输入并将其转换为字符串名称: cout << "Enter the number: "; int number; cin >> number; cout << "Enter names: "; string names; getline(cin, names); cout>number; cout>number命令在getline()命令之前,但是(我猜这就是问题所在),它不允许我输入名称。为什么? 我听说了一些关于cin.cl

我需要以下程序获取整行用户输入并将其转换为字符串名称:

cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;

getline(cin, names);
cout>number;
cout>number
命令在
getline()
命令之前,但是(我猜这就是问题所在),它不允许我输入名称。为什么?

我听说了一些关于
cin.clear()
命令的事情,但我不知道这是如何工作的,也不知道为什么这是必要的

cout << "Enter the number: ";
int number;
if (cin >> number)
{
    // throw away the rest of the line 
    char c;
    while (cin.get(c) && c != '\n')
        if (!std::isspace(c))
        {
            std::cerr << "ERROR unexpected character '" << c << "' found\n";
            exit(EXIT_FAILURE);
        }
    cout << "Enter names: ";
    string name;
    // keep getting lines until EOF (or "bad" e.g. error reading redirected file)...
    while (getline(cin, name))
        ...use name...
}
else
{
    std::cerr << "ERROR reading number\n";
    exit(EXIT_FAILURE);
}
用小船或类似的东西能不能更简单一些? 对于原始需求,另一个简单但不成熟的替代方法是使用
std::skipws
在读取行之前跳过任何数量的空白

if (std::cin >> number >> std::skipws)
{
    while (getline(std::cin, name))
        ...

……但是如果它像“1E6”那样输入(例如一些科学家试图输入1000000,而C++只支持浮点数字的符号)不会接受,那么你最终会得到<代码>编号<代码>设置为<代码> 1 <代码>,并且<代码> E6< /Cord> >作为代码的第一个值>名称< /C>。另外,如果您有一个有效的数字后跟一个或多个空行,这些行将被默默忽略。

另一种方法是放置一个

cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' ); 
cin.ignore(std::numeric_limits::max(),'\n');
在您的
cin>>号码之后
完全刷新输入缓冲区(在找到换行符之前拒绝所有额外字符)。您需要
#包括
以获得
max()
方法。

尝试:

int number;

cin >> number;

char firstCharacterOfNames;
cin >> firstCharacterOfNames;  // This will discard all leading white space.
                               // including new-line if there happen to be any.

cin.unget();                   // Put back the first character of the name.

std::string  names;
std::getline(cin, names);      // Read the names;
或者。如果你知道号码和名字总是在不同的行上

cin >> number;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
std::getline(cin, names);
cin>>编号;
cin.ignore(std::numeric_limits::max(),'\n');
std::getline(cin,名称);
cout>编号;
cin.ignore(256,“\n');//剩余输入字符到下一个换行符
//被忽视
不能包含
#包括
使用名称空间std;
int main()
{
数量;

cout在使用getline之前,可以使用std::ws提取输入缓冲区中的任何空白字符。std::ws的头是sstream

cout << "Enter the number: ";
int number;
cin >> number;
cout << "Enter names: ";
string names;
cin>>ws;
getline(cin, names);
cout>number;
cout>ws;
getline(cin,名称);

您可以在中找到您想要的答案

当在以空格分隔的输入之后立即使用时,例如在
int n;std::cin>>n;
之后,getline使用运算符>>在输入流上留下的结束行字符,并立即返回。常见的解决方案是使用
cin忽略输入行上的所有剩余字符。忽略(std::numeric_limits::max(),“\n”)
在切换到面向行的输入之前


也可以刷新输入缓冲区以读取字符串

fflush(标准输入法)

它在标题stdio.h中定义

这个代码有效

cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;
fflush(stdin);  //FLUSHING STDIN
getline(cin, names);
cout>number;
cout您希望在cin语句之后使用cin.ignore(),因为您希望在使用cin获取int变量后忽略缓冲区中剩余的“\n”

我有一个类似的程序,用于处理类似的问题:

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main() {
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";

    // Declare second integer, double, and String variables.
    int n;
    double d2;
    string str;

    // Read and save an integer, double, and String to your variables.
    cin >> n;
    cin >> d2;

    cin.ignore();

    getline(cin, str);

    // Print the sum of both integer variables on a new line.
    cout << i + n << endl;


    // Print the sum of the double variables on a new line.
    cout << d + d2 << endl;

    // Concatenate and print the String variables on a new line
    cout << s << str << endl;

    // The 's' variable above should be printed first.

    return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
int i=4;
双d=4.0;
字符串s=“HackerRank”;
//声明第二个整数、双精度和字符串变量。
int n;
双d2;
字符串str;
//读取并将整数、双精度和字符串保存到变量中。
cin>>n;
cin>>d2;
cin.ignore();
getline(cin,str);
//在新行上打印两个整数变量之和。
我刚才用过

getline(cin >> ws,lard.i_npute);
符合标准

#include <iostream>
#包括

在我遇到回车和ws操纵器工作问题的实例中,我可能会开始将循环函数作为类嵌入,并至少使用构造函数和析构函数调用。

从概念上讲,我认为您希望每个答案都整齐地排成一行。那么为什么不尝试一下呢

cout << "Enter the number: ";
string line;
getline(cin, line);
int number = std::stoi(line);

cout << "Enter names: ";
string names;
getline(cin, names);
cout
cout>number;
cout>number
uses,它在第一次使用时被分配给名称。现在重新使用getline写入正确的值。

在使用cin before getline()函数时,请尝试cin.ignore()

void inputstu(){
不能滚动;
cin.ignore();//忽略空格并输入键

cout@jonsca:“拒绝所有额外字符”在大多数生产系统中都是可疑的……可以接受空白,但丢弃未知数据很容易导致错误的结果。@cnicutar它因实现而异implementation@Tony如果在cin语句之后有一个接受字符的循环,而不是一个getline,那又如何呢你说的更多的是安全漏洞吗?“循环接受字符”…如果你是指
while(isspace(cin.peek()))cin.ignore()
…对我来说很好。在上面,我想更多的是用户误解了输入格式的要求,或者一些脚本生成了输入中断,但是中断的输入似乎被成功处理了,因为它被忽略了-他们可能最终信任中断的结果。如果输入不符合规范,最好让您的程序生成一个n错误。@Tony啊,好吧,我误解了你想说的。关于验证的观点很好。假设你键入:
5John
。然后
cin>>number
只读取5。在流中保留新行(enter)字符。因此,当你尝试用
getline(cin,name)读取名称时
它读取到行尾。但是请注意,这里有一个新行字符,可以读取(因此名称将为空(因为您没有读取5后面的新行字符)。如果要在>>和getline()之间切换您需要小心输入的行尾。@LokiAstari:这是一个比下面发布的任何一个更好的答案。您可以这样发布吗?呃,这并不能回答问题或解决问题-1@LightnessRacesinOrbit:它如何“不解决问题”?对
getline
的第一次调用会使用数字后面的换行符并循环,直到它找到一个非空行……对我来说似乎是固定的。OP的问题没有问“为什么?”问题是
#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main() {
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";

    // Declare second integer, double, and String variables.
    int n;
    double d2;
    string str;

    // Read and save an integer, double, and String to your variables.
    cin >> n;
    cin >> d2;

    cin.ignore();

    getline(cin, str);

    // Print the sum of both integer variables on a new line.
    cout << i + n << endl;


    // Print the sum of the double variables on a new line.
    cout << d + d2 << endl;

    // Concatenate and print the String variables on a new line
    cout << s << str << endl;

    // The 's' variable above should be printed first.

    return 0;
}
getline(cin >> ws,lard.i_npute);
#include <iostream>
cout << "Enter the number: ";
string line;
getline(cin, line);
int number = std::stoi(line);

cout << "Enter names: ";
string names;
getline(cin, names);
cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;
getline(cin, names);//works on the \n left behind
getline(cin, names);//continues and rewrites names
void inputstu(){
    cout << "Enter roll Number:";
    cin >> roll_no;
    cin.ignore(); //ignore the withspace and enter key
    cout << "Enter name:";
    getline(cin, stu_name);
}