0

I'm wondering what is the accepted way of getting input from the command line which captures white space as well. I thought this would do it...

char text[500];   
int textSize = 0;

int main() {

    while (!cin.eof()) {
        cin >> text[textSize];
        textSize++;
    }

    for(int i = 0; i < textSize; i++) {
        cout << text[i];
    }

return 0;
}

But looks like it skips white space. I switched to this...

char c;

while ((c = getchar()) != EOF)  {
    text[textSize] = c;
    textSize++;
}

which works perfectly but I know this from a C programming book. Wondering how I would handle it in c++

templatetypedef
  • 328,018
  • 92
  • 813
  • 992
cpd1
  • 705
  • 8
  • 27

1 Answers1

3

By default, the stream extraction operator in C++ will skip whitespace. You can control this with the noskipws stream manipulator:

while (!cin.eof()) {
    cin >> noskipws >> text[textSize];
    textSize++;
}

That said, the program you've written has a pretty clear buffer overflow problem if you read too much text. If you're planning on reading a fixed number of bytes, use istream::read. If you'd like to read a variable number of bytes, consider using a std::string in conjunction with istream::get, like this:

std::string input;
char ch;

while (cin.get(ch)) {
    input += ch;
}

This doesn't have the risk of a buffer overflow and should handle as much text as possible (subject to restrictions on available memory, of course.)

templatetypedef
  • 328,018
  • 92
  • 813
  • 992
  • Thanks! When you say risk of buffer overflow - do you mean because if the input is larger than the array, the array will not have a proper termination. I see also that you didn't actually have to provide an index to iterate when inserting into input "input += ch". When I tried printing out, I thought I could iterate through it by doing input++ but that didn't work – cpd1 Feb 06 '16 at 19:26
  • @cpd1 Yes, more or less that's what he means. The exact answer to that is that you'll get undefined behaviour when you try to do that. See this for a detailed explanation: https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why You can't do input++ because input is a string type, and the ++ operator isn't defined on strings. What is defined on strings is the + operator, which simply appends the two strings, or in this case the string and the character. – Tejas Shah Sep 27 '17 at 18:54