tags:

views:

193

answers:

4

My code has to identify whitespace characters using cin, so when I use space as an input it should identify the space. How do I do this?

+1  A: 

Use cin.getline to read the line with the space.

http://www.cplusplus.com/reference/iostream/istream/getline/

Stefan Kendall
Better use the free function than the method if you don't really need to use raw char* buffers: http://www.cplusplus.com/reference/string/getline/
sth
+2  A: 
string str;
getline(cin, str); // get the whole line

If you want to deal with c-strings you could use the mentioned cin.getline(....) which is different from strings getline.

AraK
+3  A: 

Cin breaks on whitespace, of any kind. If you need to read an entire line, you need to use the get line function:

getline(cin, line);

Where line is a std::string. This will still cut off any new lines or carriage returns.

To test the string for spaces examine every character in the string and compare it to the space character " ". That is left as an exercise for the reader ;)

Daniel Bingham
Not 100% correct. You can get the stream operators to not ignore space with std::noskipws. But std::getline() is the easiest to use solution.
Martin York
+7  A: 

You can use std::noskipws to disable the whitespace skipping that std::cin does by default:

#include <iostream>
#include <iomanip>

int main() {
  char c;
  std::cin >> std::noskipws;
  while (std::cin >> c) {
    if (c == ' ')
      std::cout << "A space!" << std::endl;
  }
  return 0;
}
sth
There are more characters that are __"White Space"__
Martin York
I couldn't agree more with Martin. Why not using `std::isspace()` instead?
sbi
The question mentions "whitespace" as well as "space" and is not very clear about the details of what needs to be done with it. Only the OP knows what exactly he wants do do inside the loop, the main point I wanted to make was that you can disable skipping of whitespace with `noskipws`. What you then do with it depends on the specific problem you're trying to solve.
sth