Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;二进制到十进制转换器输入仅接受1或0_C++ - Fatal编程技术网

C++ c++;二进制到十进制转换器输入仅接受1或0

C++ c++;二进制到十进制转换器输入仅接受1或0,c++,C++,您好,我正在尝试做一个将二进制数转换为十进制数的编程赋值。问题是,我必须将用户输入作为一个sting,如果用户输入中存在除1或0以外的任何内容,则应该给出一条错误消息,然后提示他们提供新的输入。我已经试了一段时间了,但我似乎做不好。有人能帮我吗? 到目前为止,这是我最好的尝试,它会将字符串的每个输入都运行到if语句中,但它似乎只关心最后一位数字,我想不出一种方法来实现它,因此,如果有一个错误,它将保持while loop语句为true以继续运行 #include <iostream>

您好,我正在尝试做一个将二进制数转换为十进制数的编程赋值。问题是,我必须将用户输入作为一个sting,如果用户输入中存在除1或0以外的任何内容,则应该给出一条错误消息,然后提示他们提供新的输入。我已经试了一段时间了,但我似乎做不好。有人能帮我吗? 到目前为止,这是我最好的尝试,它会将字符串的每个输入都运行到if语句中,但它似乎只关心最后一位数字,我想不出一种方法来实现它,因此,如果有一个错误,它将保持while loop语句为true以继续运行

#include <iostream>
#include <string>
using namespace std;

string a;

int input();

int main()
{
    input();
    int stop;
    cin >> stop;
    return 0;
}

int input()
{
    int x, count, repeat = 0;

    while (repeat == 0)
    {
        cout << "Enter a string representing a binary number => ";
        cin >> a;
        count = a.length();
        for (x = 0; x < count; x++)
        {

            if (a[x] >= '0' &&a[x] <= '1')
            {
                repeat = 1;
            }
            else
                repeat = 0;
        }

    }

    return 0;
}

    return 0;
}
#包括
#包括
使用名称空间std;
字符串a;
int输入();
int main()
{
输入();
int stop;
cin>>停止;
返回0;
}
int输入()
{
整数x,计数,重复=0;
while(repeat==0)
{
cout>a;
计数=a.长度();
对于(x=0;x如果(a[x]>='0'&&a[x]将for循环更改为:

    count = a.length();
    repeat = 1;
    for (x = 0; x < count; x++)
    {

        if (a[x] != '0' && a[x] != '1')
        {
            repeat = 0;
            break;
        }
    }
count=a.length();
重复=1;
对于(x=0;x

其思想是,首先假定
repeat
为1(因此您假定您的输入是有效的)。随后,如果您的输入字符中有一个不是0或1,则将
repeat
设置为0并退出循环(无需继续查找其他字符)

全局变量是非常糟糕的形式,我现在要戒掉这个习惯。