[英]c++ binary to decimal converter input to only accept 1 or 0
Hello I am trying to do a programming assignment that converts a binary number to a decimal. 您好,我正在尝试进行将二进制数字转换为十进制的编程任务。 The problem states that I have to get the users input as a sting and if there is anything other than a 1 or a 0 in the users input it should give an error message then prompt them to give a new input.
问题表明,我必须以字符串形式输入用户输入,如果用户输入中除了1或0以外的其他内容,它应该给出错误消息,然后提示他们输入新的信息。 I have been trying for a while now and I cant seem to get it right can anyone help me?
我已经尝试了一段时间,但似乎无法正确解决,有人可以帮助我吗? so far this is my best attempt it will run every input of the string into a if statement but it only seems to care about the last digit i cant think of a way to make it so if there is a single error it will keep while loop statement as true to keep going.
到目前为止,这是我的最佳尝试,它将字符串的每个输入运行到if语句中,但它似乎只关心最后一位,我想不出一种方法来制作它,因此,如果存在单个错误,它将在while循环中保留声明为真,继续前进。
#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;
}
Change your for loop as this: 如下更改您的for循环:
count = a.length();
repeat = 1;
for (x = 0; x < count; x++)
{
if (a[x] != '0' && a[x] != '1')
{
repeat = 0;
break;
}
}
The idea is that repeat
is assumed to be 1 at first (so you assume that your input is valid). 这个想法是,首先假定
repeat
为1(因此您假设输入有效)。 Later on, if any of your input characters is not a 0 or 1, then you set repeat
to 0 and exit the loop (there's no need to keep looking for another character) 稍后,如果您输入的任何字符都不为0或1,则将
repeat
设置为0并退出循环(无需继续寻找其他字符)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.