gpt4 book ai didi

C++填充数组问题

转载 作者:行者123 更新时间:2023-11-28 03:20:18 25 4
gpt4 key购买 nike

我有一个根据用户输入填充数组的函数

该程序在此测试用例中运行良好,但它要求用户输入的数字比需要的多。

void fill_array(char a[], int size)
{
char next;
const char SENTIEL ='.';
int index=0;
cin >> next;


while ((next !=SENTIEL) && (index < size))
{
a[index] = next;
index++;
cin >> next;

}

cout << a[0];
cout << a[1];
cout << a[2];
cout << a[3];
cout << a[4];
cout << a[5];
cout << a[6];
cout << a[7];
cout << a[8];
cout << a[9];
}




int main()
{
int const MAX=10;
char b[MAX];
fill_array(b,MAX);
}

这会返回正确的数字,但还有一个要问。

最佳答案

您在循环外请求 cin >> next(1 次)然后您请求 cin >> next size 时间这导致:大小 + 1 倍。

您应该使用 for 循环(当然还要删除局外人 cin >> next):

for (int index = 0; (next !=SENTIEL) && (index < size); index++)
{
a[index] = next;
cin >> next;
}

关于C++填充数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15631413/

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