简体   繁体   English

为什么 getline 跳过第一行?

[英]Why getline skips first line?

In the following code, getline() skips reading the first line.在以下代码中, getline()跳过读取第一行。 I noted that when commenting the " cin >> T " line, it works normally.我注意到在注释“ cin >> T ”行时,它正常工作。 But I can't figure out the reason.但我想不出原因。

I want to read an integer before reading lines!我想在读行之前读一个整数! How to fix that?如何解决?

#include <iostream>
using namespace std;

int main () {
    int T, i = 1;
    string line;

    cin >> T;

    while (i <= T) {
        getline(cin, line);
        cout << i << ": " << line << endl;
        i++;
    }

    return 0;
}
cin >> T;

This consumes the integer you provide on stdin.这会消耗您在标准输入上提供的整数。

The first time you call:第一次调用:

getline(cin, line)

...you consume the newline after your integer. ...您在整数后使用换行符。

You can get cin to ignore the newline by adding the following line after cin >> T;您可以通过在cin >> T;之后添加以下行来让cin ignore换行符cin >> T; :

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

(You'll need #include <limits> for std::numeric_limits ) (对于std::numeric_limits您需要#include <limits>

Most likely there is a newline in your input file, and that is being processed immediately, as explained on this page:您的输入文件中很可能有换行符,并且正在立即处理,如本页所述:

http://augustcouncil.com/~tgibson/tutorial/iotips.html http://augustcouncil.com/~tgibson/tutorial/iotips.html

You may want to call cin.ignore() to have it reject one character, but, you may want to read more of the tips, as there are suggestions about how to handle reading in numbers.您可能想要调用cin.ignore()让它拒绝一个字符,但是,您可能想要阅读更多提示,因为有关于如何处理数字读取的建议。

This line only reads a number:这一行只读取一个数字:

cin >> T;

If you want to parse user input you need to take into account they keep hitting <enter> because the input is buffered.如果你想解析用户输入,你需要考虑到他们不断点击 <enter> 因为输入被缓冲。 To get around this somtimes it is simpler to read interactive input using getline.为了解决这个问题,有时使用 getline 读取交互式输入更简单。 Then parse the content of the line.然后解析该行的内容。

std::string userInput;
std::getline(std::cin, userInput);

std::stringstream(userInput) >> T;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM