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?
May be you need to use a char *Line; to get the space inclusive.
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.
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.
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);
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.
#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;
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With