简体   繁体   English

C++ - Cin.fail 开始时出现空格

[英]C++ - Cin.fail when space on begining

I need help with cin.fail when it starts with a space.当 cin.fail 以空格开头时,我需要帮助。

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.当有像 1010 这样的东西时,它会告诉我号码。 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.如果它包含其他数字 - 2,3 等。它会失败,它可以但是当它得到类似 _101010 的东西时.. 程序仍然会继续,它会给我号码,但我需要它失败。 So I need something like .. when b contains 1 0 or \\n, programm will continue, otherwise it will fail.所以我需要类似 .. 当 b 包含 1 0 或 \\n 时,程序将继续,否则它将失败。 But when I put in \\n like但是当我输入 \\n 就像

if(b[i]=='1' || b[i]=='0' || b[i]=='\\n') - its not working .. I mean, programm fails in any case ... if(b[i]=='1' || b[i]=='0' || b[i]=='\\n') - 它不起作用..我的意思是,程序在任何情况下都会失败。 ..

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.如果要读取整行输入,请改用getline

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];如果你读入一个std::string而不是固定大小的char b[80];它也会更容易,更安全char b[80]; . . If you ever happen to read more than 80 characters into that, you're toast.如果你碰巧读到超过 80 个字符,那你就干杯了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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