gpt4 book ai didi

c++ - 输入 2 个非常基本的 C 字符串时无限循环

转载 作者:行者123 更新时间:2023-11-30 05:08:11 31 4
gpt4 key购买 nike

当我输入 2 个完全为 1 和 0 的字符串时,以下代码会产生一个无限循环。

我做了什么?

    char input1[9] = {'\0'};
char input2[9] = {'\0'};
bool reEnter = false;


do
{
reEnter = false;
cout << "The numbers to be added are: "<< endl;
cin.ignore();
cin.getline(input1, 9, '\0');
cin.ignore();
cin.getline(input2, 9, '\0');
for (int i = 0; i<8; i++)
{
if((input1[i] != '0') && (input1[i] != '1') || (input2[i] != '0') && (input2[i] != '1'))
{
reEnter = true;
}
}
if(reEnter == true)
cout << "Must be an 8 bit binary" << endl;
}while(reEnter == true);

最佳答案

这就明白了。出于某种原因,它不喜欢忽略,并且使用空字符终止 cin.getline 函数会创建无限循环。

char input1[9] = {'\0'};
char input2[9] = {'\0'};
bool reEnter = false;


do
{
reEnter = false;
cout << "The numbers to be added are: "<< endl;
cin.getline(input1, 9);
cin.getline(input2, 9);
for (int i = 0; i<8; i++)
{
if((input1[i] != '0') && (input1[i] != '1') || (input2[i] != '0') && (input2[i] != '1'))
{
reEnter = true;
}
}
if(reEnter == true)
cout << "Must be an 8 bit binary" << endl;
}while(reEnter == true);

关于c++ - 输入 2 个非常基本的 C 字符串时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46969761/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com