Reputation:
So I am teaching myself C++ and I cant see what is wrong here:
code:
// Arrays.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
char input = ' ';
for(i = 1; i <= 100; ++i)
{
std::cout << "enter a value for element number " << i << ": " ;
do
{
input = std::cin.get();
std::cout << "recorded element in position " << i << " is " << input << "\n";
} while (!input == 'q') ;
}
}
problem:
line 17: input std::cin.get();
It gives me this: It asks for input, then records it and automatically completes element 2 for me
enter a value for element number 1:
5 recorded element in position 1
is 5 enter a value for element number 2:recorded element in position
2 is
enter a value for element number 3:
But when I replace it with std::cin >> input
it doesn't, why?
Upvotes: 0
Views: 78
Reputation: 154035
It seems you entered a newline: when you use the return key, you'll get another character ('\n'
) which is also obtained from std::cin.get()
. The member std::istream::get()
is an unformatted input function which doesn't attempt to skip whitespace before trying to read whatever if tries to read.
On the other hand, when using formatted input, e.g., std::cin >> input
the stream will skip all leading whitespace before trying to read something. That is, the newline you also entered is skipped.
You can use (std::cin >> std::ws).get()
to have leading whitespace consumed before using get()
. ... and the other way around, you can set up the stream not skip leading whitespace automatically for formatted input using std::cin >> std::noskipws
(and reverse this setting again using std::cin >> std::skipws
). In general it isn't advisable to not skip leading whitespace for formatted input, though.
Upvotes: 4