gpt4 book ai didi

c++ - 如何在不遍历全长的情况下仅将数组迭代到填充的位置

转载 作者:行者123 更新时间:2023-11-28 04:56:40 24 4
gpt4 key购买 nike

I like to fill this array to only up to a[4] and want to traverse only up to 4th position not the enire length.

 int main()
{
int a[10],i,j=0;
cout<<"\nEnter 4 number :";
for(i=0;i<4;i++)
{
cin>>a[i];
}
while(a[j]!='\0')
{
cout<<a[j];
j++;
}

}

this code prints 11 numbers

最佳答案

如果你可以使用一个特殊的值,比如零,来表示项目结束,方式'\0'在 C 字符串中使用,您可以在初始化后使用您的方法 a归零:

int a[10] = {0};
...
while (a[j]) {
cout << a[j++];
}

这种方法的缺点是结束标记在输入中变得无效。换句话说,如果最终用户在四个输入中输入一个零,打印将在打印少于四个项目后停止。

这就是为什么这两种方法更常见:

  • 使用动态容器,例如 std::vector<int> - 此方法仅在 C++ 中有效
  • 将项目数存储在单独的变量中 - 如果您必须使用“原始”数组,这种方法是最常见的。

关于c++ - 如何在不遍历全长的情况下仅将数组迭代到填充的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46989908/

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