简体   繁体   English

数组超出应有的水平

[英]array getting more than it should

char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(cin.getline(name[count++],20))
 ;
--count;

(rest of code is for printing if u need to see that too it's at the end) (其余的代码用于打印,如果您也需要在末尾看到的话)

when i Enter names more than 4 it still prints those names but how can that happen? 当我输入的名称超过4个时,它仍会打印这些名称,但是怎么办? because the first dimension is 4 so how can it get more than four 因为第一个维度是4,所以它怎么能超过四个

printing part of code:

for(int i=0; i<count; i++)
{
        cout<<i<<"="<<name[i]<<endl;
}
system("pause");
}

You need to tell the while() loop when to stop. 您需要告诉while()循环何时停止。

Try this: 尝试这个:

char name[4][20];
int count=0;
cout<<"Enter 4 name at most , one name per line:\n";
while(count < 4 && cin.getline(name[count++],20))
    ;

If I get it correctly, your are asking "why if the array is 4 I can fit 5?". 如果我没弄错,您会问“为什么数组是否为4我可以容纳5?”。
Unlike Pascal, where arrays boundaries are checked at runtime, C++ doens't do such thing. 与Pascal不同,Pascal在运行时检查数组边界,而C ++则不会这样做。

Think about it. 想一想。 An array is just some pointer that is added the offset later. 数组只是一些指针,稍后会添加偏移量。
Let's say that you've an array of 5 integers and you do this 假设您有一个由5个整数组成的数组,然后执行此操作

int a[5];
a[3] = 3;
a[6] = 4;

Nothing is really wrong, because in the first assignment, the statement equals to a+12 and the second one a+24 . 没什么错,因为在第一个赋值中,该语句等于a+12 ,第二个等于a+24 You're just incrementing the pointer and unless you don't bother the OS, you could go on and potentially overwrite some other data. 您只是在增加指针,除非您不打扰操作系统,否则您可能会继续并可能覆盖其他一些数据。
So C++ will very unlikely say something if you cross the arrays boundaries. 因此,如果您跨越数组边界,C ++几乎不会说什么。 This implies that you must always somehow know how big is the array, in your case by simply adding to the loop: 这意味着您必须始终以某种方式知道该数组的大小,只需添加到循环中即可:

while(count < 4 && cin.getline(name[count++], 20));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM