Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cin.get() in a loop

Tags:

c++

cin

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.

like image 368
Kudayar Pirimbaev Avatar asked Feb 27 '13 20:02

Kudayar Pirimbaev


People also ask

What is the use of CIN get ()?

get() is used for accessing character array. It includes white space characters. Generally, cin with an extraction operator (>>) terminates when whitespace is found.

How do you use CIN in a while loop?

Just add the cin inside the while loop, and the program will always wait you to write something. Example: int i; do{ cin>>i cout<<"num is smaller than 100"; } while(i<100); (Btw, idk if this code actually works.)

Does CIN get () Read newline?

getline(cin, newString); begins immediately reading and collecting characters into newString and continues until a newline character is encountered. The newline character is read but not stored in newString.

Is Cin get same as CIN Getline?

cin. get() takes the input of whole line which includes end of line space repeating it will consume the next whole line but getline() is used to get a line from a file line by line.


1 Answers

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&).

like image 89
Robᵩ Avatar answered Sep 22 '22 00:09

Robᵩ