简体   繁体   中英

C++ - Cin.fail when space on begining

I need help with cin.fail when it starts with a space.

This is what I mean.

#include <iostream>
#include <math.h>

using namespace std;

int main ()
{
    char b[80];
    int e,d,v,m=0;

    for(int i=0;i<80;i++)
    {
        b[i]=0;
    }

    cout << "Insert number in binary:" << endl;
    cin >> b;

    v=0;
    for(int i=0;i<80;i++)
    {
        if(b[i]=='1' || b[i]=='0' || b[i]=='\n')
        {
        v++;
        }
        else if(b[i]!=0 || b[i]!='\0' || b[i]==' ')
        {
            cout << "Error" << endl;
            return 0;
        }
    }

    e=v-1;
    d=0;
    m=0;
    for(int i=0;i<v;i++)
    {
      m=(b[i]-48)*(pow(2,e));
      d=d+m;
      e=e-1;
    }

    cout << "His number in decimal: "<< d << endl;

    return 0;
}

When there is something like 1010 it OK, it will give me number. If it contains other number - 2,3 etc.. it will fail, its OK But when it get something like _101010 .. programm will still proceed and it will give me number, but I need it to fail. So I need something like .. when b contains 1 0 or \\n, programm will continue, otherwise it will fail. But when I put in \\n like

if(b[i]=='1' || b[i]=='0' || b[i]=='\\n') - its not working .. I mean, programm fails in any case ...

Sorry for asking on this "stupid" question, but I am doing it for hours and still didnt figure it out .. Thanks guys.

cin >> b; will skip leading whitespace and then read the next word. That's how it is designed.

If you want to read an entire line of input, use getline instead.

It will also be much easier, and a lot safer, if you read into a std::string instead of a fixed size char b[80]; . If you ever happen to read more than 80 characters into that, you're toast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM