简体   繁体   中英

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.

Subsequently, this line:

cin.get (a, 10);

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.

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');

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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