[英]How do i store user input in an array?
為什么我的函數不接受任何輸入和輸出任何東西? 我希望能夠接收用戶輸入,將其存儲在我的數組中,然后打印出存儲的值。
using namespace std;
void Memory(){
int temp;
int Mange[3] = {0, 0, 0};
for(int i = 0; i < sizeof(Mange); i++){
cin >> temp;
temp = Mange[i];
cout << Mange[i];
}
}
int main() {
Memory();
return 0;
}
如果您剛剛開始熟悉使用數組,這是一個很好的練習,對您有好處! 這就是我將如何實現一個程序,該程序將接受用戶輸入到數組中,然后打印數組中的每個元素(請務必閱讀注釋!):
#include <iostream>
using namespace std;
const int MAXSIZE = 3;
void Memory(){
//initialize array to MAXSIZE (3).
int Mange[MAXSIZE];
//iterate through array for MAXSIZE amount of times. Each iteration accepts user input.
for(int i = 0; i < MAXSIZE; i++){
std::cin >> Mange[i];
}
//iterate through array for MAXSIZE amount of times. Each iteration prints each element in the array to console.
for(int j = 0; j < MAXSIZE; j++){
std::cout << Mange[j] << std::endl;
}
}
int main() {
Memory();
return 0;
}
我希望這有幫助! 了解該程序實際執行的操作的一個好方法是將其復制並粘貼到 IDE 中,然后對代碼運行調試器並逐行觀察發生的情況。
我自己起初在啟動數組時就這樣做了,然后就掌握了竅門。 你做了一半的程序正確,那很好,你犯的唯一錯誤是將輸入數據存儲在適當的變量中並以錯誤的格式顯示它們要解決這個問題,
#include<iostream>
using namespace std;
const int size=3;
void Memory()
{
// You don't need variable temp here
int Mange[size] = {0, 0, 0};
//It's not necessary to keep it zero but it's a good practice to intialize them when declared
for(int i = 0; i < size; i++)
//You can store maximum value of array in diff variable suppose const then use it in condition
{
cin >> Mange[i];
cout << Mange[i];
//You can print it later with a different loop
}
}
int main() {
Memory();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.