CODE:
#include <iostream>
#define BUFF 100
using namespace std;
int main(int argc, char* argv[])
{
char input[BUFF];
cout << "Input:\n>";
cin >> input;
cout << "\n\nOutput:" << input;
cin >> input;
cin >> input;
}
How come when you read input into a char array it skips the spaces? oh and there is 2 cin’s(at the end) because it acts a little strange and exits if a space is entered when there is 1 cin…not sure why either.
EG
i enter cup cake and it outputs cup
This is basically because
operator>>forstd::cintakes one “input object” between whitespaces (i.e.,\t,\n) and reads it into given variable/object. Try:For input
cup cakeyou will getinput[0] == "cup"andinput[1] == "cake".If you don’t read whole input it stays in the input buffer; that is why you need two
cin >> inputat the end ofmain(), which made you confused. The explanation is that you read"cup"intoinput, but"cake"stays in buffer ready for next read.This behaviour is very handy when reading into several variables, e.g.:
This allows you to write three integers separated by whitespace and they’ll get read into proper variables. If you need whole line of input, try as suggested by David Rodríguez and use
std::getline.EDIT Actually, after reading
std::cin >> input[0] >> input[1]the input buffer will still not be empty since it contains an\ncharacter (after pressing ENTER). To empty input buffer try: