Reading in standard input into a char array - C++ -


i'm wondering accepted way of getting input command line captures white space well. thought it...

char text[500];    int textsize = 0;  int main() {      while (!cin.eof()) {         cin >> text[textsize];         textsize++;     }      for(int = 0; < textsize; i++) {         cout << text[i];     }  return 0; } 

but looks skips white space. switched this...

char c;  while ((c = getchar()) != eof)  {     text[textsize] = c;     textsize++; } 

which works know c programming book. wondering how handle in c++

by default, stream extraction operator in c++ skip whitespace. can control noskipws stream manipulator:

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

that said, program you've written has pretty clear buffer overflow problem if read text. if you're planning on reading fixed number of bytes, use istream::read. if you'd read variable number of bytes, consider using std::string in conjunction istream::get, this:

std::string input; char ch;  while (cin.get(ch)) {     input += ch; } 

this doesn't have risk of buffer overflow , should handle text possible (subject restrictions on available memory, of course.)


Comments

Popular posts from this blog

routing - AngularJS State management ->load multiple states in one page -

python - GRASS parser() error -

Swift game error message -