首页 文章

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

提问于
浏览
34

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

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

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

getline(cin, names);

然而,在 getline() 命令之前使用 cin >> number 命令(我允许我输入名称 . 为什么?

我听说过一个关于 cin.clear() 命令的事情,但我不知道这是如何工作的,或者为什么这甚至是必要的 .

13 回答

  • 16
    cout << "Enter the number: ";
    int number;
    cin >> number;
    
    cin.ignore(256, '\n'); // remaining input characters up to the next newline character
                           // are ignored
    
    cout << "Enter names: ";
    string names;
    getline(cin, names);
    
  • 0

    另一种方法是做一个

    cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
    

    cin>>number; 之后完全刷新输入缓冲区(拒绝所有额外字符,直到找到换行符) . 您需要 #include <limits> 才能获得 max() 方法 .

  • 9
    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);
    }
    

    在上面的代码中,这一点......

    char c;
        while (cin.get(c) && c != '\n')
            if (!std::isspace(c))
            {
                std::cerr << "ERROR unexpected character '" << c << "' found\n";
                exit(EXIT_FAILURE);
            }
    

    ...在数字只包含空格后检查输入行的其余部分 .

    为什么不使用忽略?

    这非常冗长,所以在 >> x 之后在流上使用 ignore 是一种经常推荐的替代方法,可以将内容丢弃到下一个换行符,但是它可能会丢弃非空白内容,并且这样做会忽略文件中的损坏数据 . 您可能会也可能不关心,具体取决于文件's content'是否可信,避免处理损坏的数据等有多重要 .

    所以你何时会使用clear并忽略?

    因此, std::cin.clear() (和 std::cin.igore() )不是必需的,但对于删除错误状态很有用 . 例如,如果您想给用户很多机会输入有效数字 .

    int x;
    while (std::cout << "Enter a number: " &&
           !(std::cin >> x))
    {
        if (std::cin.eof())
        {
            std::cerr << "ERROR unexpected EOF\n";
            exit(EXIT_FAILURE);
        }
    
        std::cin.clear();  // clear bad/fail/eof flags
    
        // have to ignore non-numeric character that caused cin >> x to
        // fail or there's no chance of it working next time; for "cin" it's
        // common to remove the entire suspect line and re-prompt the user for
        // input.
        std::cin.ignore(std::numeric_limits<std::streamsize>::max());
    }
    

    用skipws或类似的东西不能简单吗?

    另一个简单但半生不熟的替代 ignore 的原始要求是在阅读行之前使用 std::skipws 跳过任意数量的空格...

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

    ...但是如果输入像"1E6"(例如某个科学家试图输入1,000,000但C只支持浮点数的表示法)赢得't accept that, you' d结束时 number 设置为 1E6 读取为 name 的第一个值 . 另外,如果您有一个有效数字后跟一个或多个空行,那么这些行将被静默忽略 .

  • 0

    尝试:

    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);
    
  • 9

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

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

    或者您可以刷新输入缓冲区以读取字符串

    fflush(stdin)

    它在头文件stdio.h中定义 .

    这段代码有效..

    cout << "Enter the number: ";
    int number;
    cin >> number;
    
    cout << "Enter names: ";
    string names;
    fflush(stdin);  //FLUSHING STDIN
    getline(cin, names);
    
  • -1
    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
    

    它非常自我解释,在流中留下了一个 cin >> number 使用的\ n,它在第一次使用时被分配给名称 . 重用getline现在写入正确的值 .

  • 0

    你可以在cppreference找到你想要的答案 .

    在以空格分隔的输入后立即使用,例如在int n之后; std :: cin >> n;,getline使用operator >>消耗输入流上留下的结束字符,并立即返回 . 一个常见的解决方案是使用cin.ignore忽略输入行上的所有剩余字符(std :: numeric_limits <std :: streamsize> :: max(),'\ n');在切换到面向行的输入之前 .

  • 0

    你想在你的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;
    }
    
  • 15

    我刚刚用过

    getline(cin >> ws,lard.i_npute);
    

    与标准

    #include <iostream>
    

    在我遇到回车问题和ws操纵器工作的情况下的 Headers . 我可能会开始将循环函数作为类嵌入并使用构造函数和析构函数调用atleast .

  • 1

    从概念上讲,我认为你希望每个答案都整齐排成一行 . 那么你为什么不尝试这个呢?

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

    代码正确地使用第一个换行符,如果行正确则给出数字,否则抛出异常 . 一切都是免费的!

  • 0

    在getline()函数之前使用cin时尝试cin.ignore()

    void inputstu(){
        cout << "Enter roll Number:";
        cin >> roll_no;
        cin.ignore(); //ignore the withspace and enter key
        cout << "Enter name:";
        getline(cin, stu_name);
    }
    
  • 1
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        cout << "Enter the number: ";
        int number;
        cin >> number;
        cout << "Enter names: ";
        string names;
    
        // USE peek() TO SOLVE IT! ;)
        if (cin.peek() == '\n') {
            cin.ignore(1 /*numeric_limits<streamsize>::max()*/, '\n');
        }
    
        getline(cin, names);
    
        return 0;
    }
    

    只需使用 cin.peek() 向前查看并查看 '\n' 是否仍留在 cin 的内部缓冲区中 . 如果是这样:忽略它(基本上跳过它)

相关问题