cin char and spaces ' '

Feb 22, 2011 at 11:19pm
So I have run into this problem a few times in class lately. I have found one way around it but wanted to see if anyone could provide a little better information.
When I go to use cin >> temp; where char = temp; Anything that I input with a space will not show up if I am to output the temp. Here are my examples of this issue:
This first we are supposed to read an input char by char and add it to a string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//Taylor Sanchez
//CSCI202
//Feb 22, 2011
#include <string>
#include <iostream>
using namespace std;

int main()
{
     char temp;                         
     string thread;
     cout<< "Type a ~ to exit";
     cin>> temp;
  while (temp!='~')
  { if (temp==' ')      //wanted to check if cin>>temp even reads the space ' '
    {
    thread+= "hello";  //it never outputs hello even if a space appears
    }
    thread+=temp;
    cin >> temp;      
  }
cout<<endl<<"thread=  " <<thread <<endl;

    return temp;     
}

With the input being: "The quick brown fox jumps over the lazy dog."
The output is like this:
taylor@taylor-Vostro-220-Series:~/csci202/6lab$ g++ char2string.cpp -o char
./taylor@taylor-Vostro-220-Series:~/csci202/6lab$ ./char
Type a ~ to exitThe quick brown fox jumps over the lazy dog.~

thread=  Thequickbrownfoxjumpsoverthelazydog.


This other example is a link to my morse code program, which I solved by using a getline(). http://www.cplusplus.com/forum/beginner/36595/


I'm mostly just curious what the issue is and if there is a way to resolve it. My lab instructor didn't have an answer for me, but they are just a student who is farther along in their degree.
Feb 22, 2011 at 11:54pm
Extraction ends when the next character is either a valid whitespace or a null character, or if the End-Of-File is reached.

Spaces are whitespace, so when cin reads the whitespace and that is the only character it has read, cin only stores '\0' (the null character)

For more reading try: http://cplusplus.com/reference/iostream/istream/operator%3E%3E/

Edit: Almost forgot to post a solution as well. To not ignore whitespace for a single char, just use cin.get(temp); http://cplusplus.com/reference/iostream/istream/get/
Last edited on Feb 22, 2011 at 11:58pm
Feb 23, 2011 at 4:37pm
Cool, thanks for the info. I'll give it a try next time I run into the problem.
Feb 23, 2011 at 9:17pm
There is also the noskipws manipulator.
Topic archived. No new replies allowed.