简体   繁体   English

循环中的cin.get()

[英]cin.get() in a loop

I was trying to read from standard input. 我试图从标准输入读取。 The first line is the number of lines that I will read. 第一行是我要读的行数。 The lines that I read next will be printed again. 我下次阅读的行将再次打印。 Here is the code: 这是代码:

#include <iostream>

using namespace std;

int main()
{
    int n;
    cin >> n;
    for (unsigned int i = 0; i < n; ++i)
    {
        char a[10];
        cin.get (a, 10);
        cout << "String: " << a << endl;
    }
    return 0;
}

When I run it and give number of lines, the program exits. 当我运行它并给出行数时,程序退出。 I haven't figured out what's going on, so I've decided to ask it here. 我还没弄清楚发生了什么,所以我决定在这里问一下。

Thanks in advance. 提前致谢。

Mixing formatted and unformatted input is fraught with problems. 混合格式化和未格式化的输入充满了问题。 In your particular case, this line: 在您的特定情况下,这一行:

std::cin >> n;

consumes the number you typed, but leaves the '\\n' in the input stream. 使用您键入的数字,但在输入流中保留'\\n'

Subsequently, this line: 随后,这一行:

cin.get (a, 10);

consumes no data (because the input stream is still pointing at '\\n' ). 不消耗任何数据(因为输入流仍然指向'\\n' )。 The next invocation also consumes no data for the same reasons, and so on. 由于相同的原因,下一次调用也不会消耗任何数据,依此类推。

The question then becomes, "How do I consume the '\\n' ?" 那么问题就变成了,“我如何消费'\\n' ?” There are a couple of ways: 有两种方法:

You can read one character and throw it away: 你可以阅读一个角色然后扔掉它:

cin.get();

You could read one whole line, regardless of length: 无论长度如何,您都可以读取整行:

std::getline(std::cin, some_string_variable);

You could ignore the rest of the current line: 您可以忽略当前行的其余部分:

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

As a bit of related advice, I'd never use std::istream::get(char*, streamsize) . 作为一些相关的建议,我永远不会使用std::istream::get(char*, streamsize) I would always prefer: std::getline(std::istream&, std::string&) . 我总是喜欢: std::getline(std::istream&, std::string&)

cin.get(a, 10) cin.get()之前添加cin.get()将解决您的问题,因为它将读取输入流中的剩余endline。

我认为在使用cin时了解这一点非常重要: http//www.cplusplus.com/forum/articles/6046/

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

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