有問題少數到目前爲止,象變量「X」的多個聲明和missuses; for循環可能不應該使用x,因爲它已經被定義,並且x在未初始化時不應該是數組大小。
至於你想做什麼,這是很難說,但我想我可以幫助。
int main()
{
const int ARRAY_SIZE = 1000; //initialize so it doesn't end up being either 0 or literally anything
int myArray[ ARRAY_SIZE ];
for(int x = 0; x < ARRAY_SIZE; x++)
{
cin >> myArray[ x ];
}
return 0;
}
現在通過1000次這樣的循環會要求一個數字輸入,直到陣列寫飽滿,如果你希望能夠阻止數組你將不得不添加的方式來打破for循環並記錄停止的地方。
int main()
{
const int ARRAY_SIZE = 1000;
int myArray[ ARRAY_SIZE ];
int arrayEnd = 0;
for(int x = 0; x < ARRAY_SIZE; x++)
{
int inputBuffer = 0; // this variable saves the users input and checks to see if the user wants to exit before saving the variable to myArray.
cin >> inputBuffer;
if(inputBuffer != -1) // -1 is just a value the user enters to stop the loop, choose any number you want for this.
{
myArray[ x ] = inputBuffer;
}
else
{
arrayEnd = x;
break; // stops the for loop if the number above is entered.
}
}
if(arrayEnd == 0)
{
arrayEnd = ARRAY_SIZE;
}
return 0;
}
如果你想忠實地無限或整數一個更具延展性陣列可以新 int數組設置數組的大小,像這樣
int main()
{
int* myArray = nullptr;
int arraySize = 0;
cin >> arraySize;
myArray = new int[ arraySize ];
for(int x = 0; x < arraySize; x++)
{
cin >> myArray[ x ];
}
delete[] myArray;
return 0;
}
,但我不會」如果你沒有大部分的基礎知識,那麼建議使用new,因爲new很容易導致內存泄漏,並且要記住更多的小事情。
你想存儲的字符串,或者乾脆打印他們? – pushkin
This'int x; int數組[x];'只會給你帶來痛苦。一方面它不會在所有編譯器上編譯,因爲x不是一個常量,但更重要的是,x沒有被賦值,所以如果這樣做編譯,數組的大小是不確定的。 – user4581301
@ user4581301我想回應字符串:如果輸入是數字,請做y,如果沒有,請做x。這是我的另一個問題,但我認爲我一次只能提出一個問題。在這個特定的問題中,我不確定如何實際輸入無限的字符串,以及如何按順序掃描它們。 – NinaPortman