Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cin Space in c++?

Tags:

c++

spaces

cin

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?

like image 374
Narek Avatar asked May 04 '10 13:05

Narek


People also ask

How do I give space in Cin?

May be you need to use a char *Line; to get the space inclusive.

Can CIN take spaces?

You can use cin but the cin object will skip any leading white space (spaces, tabs, line breaks), then start reading when it comes to the first non-whitespace character and then stop reading when it comes to the next white space. In other words, it only reads in one word at a time.

Can we use \n In Cin?

Essentially, for std::cin statements you use ignore before you do a getline call, because when a user inputs something with std::cin , they hit enter and a '\n' char gets into the cin buffer. Then if you use getline , it gets the newline char instead of the string you want. So you do a std::cin.

How do you put a space in a string?

Once the character is equal to New-line ('\n'), ^ (XOR Operator ) gives false to read the string. So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);


3 Answers

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 (\n) or after n-1 chars. It stops early so that it can append the null character (\0) to the array. You can read more about the istream interface here.

like image 158
rcollyer Avatar answered Oct 12 '22 09:10

rcollyer


#include <iostream>
#include <string>

int main()
{
   std::string a;
   std::getline(std::cin,a);
   for(std::string::size_type i = 0; i < a.size(); ++i)
   {
       if(a[i] == ' ')
          std::cout<<"It is a space!!!"<<std::endl;
   }
   return 0;
}
like image 43
sbi Avatar answered Oct 12 '22 09:10

sbi


To input AN ENTIRE LINE containing lot of spaces you can use getline(cin,string_variable);

eg:

string input;
getline(cin, input);

This format captures all the spaces in the sentence untill return is pressed

like image 34
Nidhin David Avatar answered Oct 12 '22 09:10

Nidhin David