[英]Iterating through array using loop in c++ and program says “exit status -1”?
因此,我嘗試使陣列適應我的硬件任務。 我有兩個循環。 First循環遍歷整個序列,這很好,我想我也不知道。 然后第二個循環應該顯示用戶輸入的所有輸入,具體取決於size_of_array的大小(在這種情況下為5,因此用戶輸入的車輛數應為5輛)。
當我運行它時,第一部分在接受輸入方面效果很好,但是第二部分卻嚇了一跳,並給了我“退出狀態-1” wtf?!?!?!!!! ??!
感謝幫助:
#include <iostream>
using namespace std;
int main()
{
int size_of_array = 5;
string ideal_cars[size_of_array];
int count;
for (count = 1; count <= size_of_array; count++)
{
cout << "Enter car number " << count << "." << "\n";
cin >> ideal_cars[count];
}
for (count = 0; count <= size_of_array; count++)
{
cout << "You entered " << ideal_cars[count] << ".";
}
}
數組的第一個索引為0,因此當size_of_array
為5時,可能的索引為0、1、2、3、4。
ideal_cars[0]
。 ideal_cars[1]
。 ideal_cars[2]
。 ideal_cars[3]
。 ideal_cars[4]
。 ideal_cars[5]
超出范圍,不允許使用。 有關圖形說明,請參見http://www.cplusplus.com/doc/tutorial/arrays 。
因此,在您的for循環中,您需要確保count
小於並且不等於size_of_array
:
for (count = 0; count < size_of_array; count++)
例:
#include <iostream>
using namespace std;
int main()
{
int size_of_array = 5;
string ideal_cars[size_of_array];
int count;
for (count = 0; count < size_of_array; count++)
{
cout << "Enter car number " << count << "." << endl;
cin >> ideal_cars[count];
}
for (count = 0; count < size_of_array; count++)
{
cout << "You entered " << ideal_cars[count] << "." << endl;
}
return 0;
}
演示: https : //ideone.com/LWbSeu 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.