簡體   English   中英

用戶輸入數組

[英]User Input into an Array

為什么不將54321的用戶整數單獨放入數組integer[1][5]中,如[5][4][3][2][1] 而是將54321放入一個數組塊中。

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int integer[1][5];
    int number;

    cout << "Please enter an integer: " << endl;

    for (int i = 0; i < 1; i++)
    {
        {
            for (int j = 0; j < 5; j++)
                cin >> integer[i][j];
        }
        cout << endl;
    }

    for (int i = 0; i < 1; i++)
    {
        {
           for (int j = 0; j < 5; j++)
                cout << integer[i][j]<< " ";
        }
        cout << endl;
    }

    system("pause");
    return 0;
}
//why wont this output an integer of 12345 individually into an array of [1][5]?

請測試這個新代碼,我已經使用字符數組來獲取輸入 12345 然后將其轉換為整數數組,然后以相反的順序打印以實現您需要的內容,您可以在第二個 for 循環中將 12345 的位置更改為 54321,然后修改第三個循環打印從 j=0 到 j<5 的數字

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    char cinteger[5];
    int number[5];

    cout << "Please enter an integer: " << endl;

    for (int j = 0; j < 5; j++)
        cin >> cinteger[j];

    for (int j = 0; j < 5; j++)
    {
        number[j]= cinteger[j] - '0';
    }
    cout << endl;

    for (int j = 5; j > 0; j--){
        cout << "[";
        cout << number[j-1]<< "] ";
    }
    cout << endl;

    return 0;
}

54321 本身被認為是一個整數。 在這種情況下,為了在數組中實現 [5][4][3][2][1],用戶必須單獨鍵入每個整數。 5輸入4輸入3輸入2輸入1輸入

這是因為您要輸入的每個數字之間必須有空格(或白色字符)。 解析器將其視為一個數字而不是五位數......

您接收輸入的方法要求您在每次提交每個整數后按“輸入”。

要么使用不同的方法從用戶那里獲取數據,要么期望用戶在每個單獨的整數后按 Enter。

如果您想繼續使用 std::cin,另一種方法是在 for 循環之前、提示之后立即獲取數據,然后使用 for 循環找到您想要的單個整數。

示例:查找 1 的數字。

int data[5], input, size;

cout<<"Enter the data: ";
cin>>input;

for(size = 0; size < 5; ++size){//Assumes array limit = 5.
    data[size] = input%10;
    input = input/10;
    if(input==0)
        break;//Escape if fewer characters than 5 entered.
}

請記住,索引 0 將包含您的最小數字,而索引 5 將包含您最大的數字:“21,354”將存儲為 {4,5,3,1,2},其中值 5 位於索引 1。因此打印將需要一個反向 for 循環。

像這樣的東西:

for(int i = size; i >= 0; --i){
    cout<<data[i]<<' ';
}
cout<<endl;

您錯誤地聲明了二維數組以獲得您想要的結果。 嘗試切換您的陣列,使其看起來像這樣。

int integer[5][1];

這也是更好地理解基本數組功能的一個很好的參考。 http://www.cplusplus.com/doc/tutorial/arrays/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM