作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
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/
我是一名优秀的程序员,十分优秀!