34

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?

Narek
  • 38,779
  • 79
  • 233
  • 389
  • As far as i can remember the space (whitespace?) is used to separate the different inputs. May be you need to use a char *Line; to get the space inclusive. – khmarbaise May 04 '10 at 13:06
  • 4
    Please change `<<<` to `<<` and use `==` to test for equality. These typos are distracting the answers. – Geoff May 04 '10 at 13:42
  • Note: The term command line is not really relevant here. The command line is converted into parameters passed to main() as the argv parameters. std::cin reads from the standard input (which by default is connected to the user keyboard). – Martin York May 04 '10 at 14:06

8 Answers8

48

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.

rcollyer
  • 10,475
  • 4
  • 48
  • 75
  • 2
    @dylnmc did you read the post? You would have noticed, then, that I state `cin.get` returns `n - 1` chars from the stream. – rcollyer Apr 19 '15 at 02:51
  • @dylnmc you've missed the point. `n` is a placeholder for whatever you want it to be as long as it is a positive integer. That's it. No great mystery. – rcollyer Apr 19 '15 at 03:33
  • 1
    I didn't realize at first it was an int. I was in a rush because I have a project due. Sorry; my comment is a little brusque, however. I'm a little tired, but no excuses. I was quite frustrated with my program and in no way meant to be hurtful. I didn't know if n was perhaps something other than an int. – dylnmc Apr 19 '15 at 05:28
  • 1
    @dylnmc that's why I included a link to the documentation, so that you could alleviate any additional confusion. In particular, here are the docs for [`get`](http://www.cplusplus.com/reference/istream/istream/get/) and the doc for [`streamsize`](http://www.cplusplus.com/reference/ios/streamsize/). Apology accepted. – rcollyer Apr 19 '15 at 20:43
  • sorry for that! I think I had been awake for 3 days working on a school project (when my teammates had dropped the ball). Thanks for your understanding. – dylnmc Sep 29 '16 at 02:24
  • @dylnmc since I was usually the one dropping the ball, my apologies to you. :) – rcollyer Sep 29 '16 at 02:43
  • "It skips all whitespace". It's worth noting that `iostream`s have formatted methods, which ignore whitespace by default, and unformatted methods, which don't. `>>` is formatted, `.get` is not. I wouldn't recommend messing with stream states unless needed, prefer to use `std::getline` – Mooing Duck Feb 20 '19 at 01:47
21
#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;
}
Brian Neal
  • 31,821
  • 7
  • 55
  • 59
sbi
  • 219,715
  • 46
  • 258
  • 445
  • I want to use char, but not std::string. I am interrested to do what I want with char[]. Any way, thanks. – Narek May 05 '10 at 06:57
  • you can still get to the characters via the c_str() function or via the [] operator which is displayed in this answer. string will also provide you with a bunch of helpful functions: http://www.cplusplus.com/reference/string/string/ – default May 05 '10 at 07:18
  • 1
    @Narek: I hope you have a very good reason to want to deal with naked `char` buffers and I hope you know more about them than you know about iostreams. – sbi May 05 '10 at 09:02
  • @Narek: Then rcollyer's answer is what you need to read individual characters. It's got my vote. – sbi May 06 '10 at 10:29
8

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

Nidhin David
  • 2,426
  • 3
  • 31
  • 45
5

Use cin.get() to read the next character.

However, for this problem, it is very inefficient to read a character at a time. Use the istream::read() instead.

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

And use == to check equality, not =.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
4

Using cin's >> operator will drop leading whitespace and stop input at the first trailing whitespace. To grab an entire line of input, including spaces, try cin.getline(). To grab one character at a time, you can use cin.get().

Odrade
  • 7,409
  • 11
  • 42
  • 65
  • 4
    Note that `std::istream::getline()` deals with character buffers and thus comes with the risk of buffer overflows. Better use `std::getline(std::istream&,std::string&,char c=' ')` from ``. – sbi May 04 '10 at 13:15
  • 2
    @sbi: Shouldn't the last parameter be `char c = '\n'`? – tiftik May 04 '10 at 13:42
  • 1
    The >> operator will drop leading white space read the target object using white space as a delimiter (so for standard PODs will stop reading the target at the first space). (So it does not 'terminate' at the first white space). Also note, be very careful in the usage of the term 'terminate' it has a very explicit meaning when talking about C++ – Martin York May 04 '10 at 14:04
  • @tiftik: Indeed. I'm sorry I blew that. – sbi May 05 '10 at 08:59
3

I thought I'd share the answer that worked for me. The previous line ended in a newline, so most of these answers by themselves didn't work. This did:

string title;
do {
  getline(cin, title);
} while (title.length() < 2);

That was assuming the input is always at least 2 characters long, which worked for my situation. You could also try simply comparing it to the string "\n".

Jacob
  • 527
  • 1
  • 5
  • 14
2

Try this all four way to take input with space :)

#include<iostream>
#include<stdio.h>

using namespace std;

void dinput(char *a)
{
    for(int i=0;; i++)
    {
        cin >> noskipws >> a[i];
        if(a[i]=='\n')
        {
            a[i]='\0';
            break;
        }
    }
}


void input(char *a)
{
    //cout<<"\nInput string: ";

    for(int i=0;; i++)
    {
        *(a+i*sizeof(char))=getchar();

        if(*(a+i*sizeof(char))=='\n')
        {
            *(a+i*sizeof(char))='\0';
            break;
        }

    }
}



int main()
{
    char a[20];

    cout<<"\n1st method\n";
    input(a);
    cout<<a;

    cout<<"\n2nd method\n";
    cin.get(a,10);
    cout<<a;

    cout<<"\n3rd method\n";
    cin.sync();
    cin.getline(a,sizeof(a));
    cout<<a;

    cout<<"\n4th method\n";
    dinput(a);
    cout<<a;

    return 0;
}
Abhishek Sahay
  • 141
  • 1
  • 9
0

I have the same problem and I just used cin.getline(input,300);.

noskipws and cin.get() sometimes are not easy to use. Since you have the right size of your array try using cin.getline() which does not care about any character and read the whole line in specified character count.

HamzeLue
  • 311
  • 3
  • 8