cin.get()循环执行 [英] cin.get() in a loop

查看:180
本文介绍了cin.get()循环执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从标准输入中读取内容。第一行是我将要阅读的行数。我接下来阅读的行将再次打印。以下是代码:

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.

预先感谢。

推荐答案

混合格式化和未格式化的输入充满了问题。在您的特定情况下,此行:

Mixing formatted and unformatted input is fraught with problems. In your particular case, this line:

std::cin >> n;

使用您输入的数字,但保留'\n'在输入流中。

consumes the number you typed, but leaves the '\n' in the input stream.

随后,此行:

cin.get (a, 10);

不使用任何数据(因为输入流仍指向'\ n')。出于相同的原因,下一次调用也不会消耗任何数据,依此类推。

consumes no data (because the input stream is still pointing at '\n'). The next invocation also consumes no data for the same reasons, and so on.

然后问题变成:我如何消耗'\ \n'?有两种方法:

The question then becomes, "How do I consume the '\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');

作为一些相关建议,我永远不会使用 std :: istream :: get(char *,streamsize)。我总是喜欢: std :: getline(std :: istream& ;, std :: string&)

As a bit of related advice, I'd never use std::istream::get(char*, streamsize). I would always prefer: std::getline(std::istream&, std::string&).

这篇关于cin.get()循环执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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