Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

How to cin Space in c++?

Say we have a code:

int main()
{
   char a[10];
   for(int i = 0; i < 10; i++)
   {
       cin>>a[i];
       if(a[i] == ' ')
          cout<<"It is a space!!!"<<endl;
   }
   return 0;
}

How to cin a Space symbol from standard input? If you write space, program ignores! :( Is there any combination of symbols (e.g. 's' or something like this) that means "Space" that I can use from standard input for my code?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It skips all whitespace (spaces, tabs, new lines, etc.) by default. You can either change its behavior, or use a slightly different mechanism. To change its behavior, use the manipulator noskipws, as follows:

 cin >> noskipws >> a[i];

But, since you seem like you want to look at the individual characters, I'd suggest using get, like this prior to your loop

 cin.get( a, n );

Note: get will stop retrieving chars from the stream if it either finds a newline char ( ) or after n-1 chars. It stops early so that it can append the null character () to the array. You can read more about the istream interface here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...