为什么getline跳过第一行? [英] Why getline skips first line?

查看:782
本文介绍了为什么getline跳过第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中, getline()跳过读取第一行。
我注意到,当评论 cin>> T 行时,它正常工作。但我不能弄清楚原因。

In the following code, getline() skips reading the first line. I noted that when commenting the "cin >> T" line, it works normally. 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;

这会消耗您在stdin上提供的整数。

This consumes the integer you provide on stdin.

第一次呼叫:

getline(cin, line)

您可以在整数后面使用换行符。

...you consume the newline after your integer.

$ c> cin 到 <$ c $通过在 cin>>>之后添加以下行,c>忽略 T; ::

You can get cin to ignore the newline by adding the following line after cin >> T;:

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

(您需要 #include< limits> std :: numeric_limits

这篇关于为什么getline跳过第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆