开发者

std::cin into char array skips spaces?

CODE:

#include <iostream>

#define BU开发者_Go百科FF 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


The question is what is it that you want to read? If you want to read a line, you should use getline, if possible the one that takes a std::string as it will grow the string as needed:

#include <iostream>
#include <string>
int main() {
   std::string line;
   std::getline( std::cin, line );
}


This is basically because operator>> for std::cin takes one "input object" between whitespaces (i.e. , \t, \n) and reads it into given variable/object. Try:

std::string input[2];
std::cout << "Input:\n>";
std::cin >> input[0] >> input[1];

For input cup cake you will get input[0] == "cup" and input[1] == "cake".

If you don't read whole input it stays in the input buffer; that is why you need two cin >> input at the end of main(), which made you confused. The explanation is that you read "cup" into input, but "cake" stays in buffer ready for next read.

This behaviour is very handy when reading into several variables, e.g.:

int a, b, c;
std::cin >> a >> b >> c;

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 \n character (after pressing ENTER). To empty input buffer try:

std::cin.clear(); // optional, use when input has gone bad; clears error flags
std::cin.sync(); // empty buffer
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜