簡體   English   中英

在char數組中輸入數字

[英]Inputting numbers in char array

關於此問題,我需要在程序中輸入100位數字並對其執行操作。 我想我會用一個char數組來做到這一點。

我嘗試了一段時間后寫了這段代碼。

 int main()
 {
 //int cases=10;

//while(cases--)
//{
    int i;
    char totalapples[102];
    //char klaudia_apples[200] , natalia_apples[200];

    for(i=0;totalapples[i]!='\0';i++)
    {
            cin>>totalapples[i];
    }

    //cin>>moreapples[200];
    //cout<<moreapples[200];

    while(i--)
    {
      cout<<totalapples[i];
    }
//}

    return 0;
  }

運行此命令時,將得到以下結果:

Input : 1234657891234567981345698
Output : 987564321

任何人都可以告訴發生了什么事嗎?

您的程序調用未定義的行為。 盡管char數組包含未定義的值,您仍然嘗試使用

totalapples[i]!='\0'

在您的for循環中。 相反,將整個字符串讀入std::string

string totalApplesStr;
cin >> totalApplesStr;

現在您可以遍歷totalApplesStr

for (char c : totalApplesStr) {
     /* Do whatever you need to */
}

或者,如果這不是代碼中的邏輯錯誤,則可以從頭到尾進行迭代:

for (auto it = totalApplesStr.rbegin(); it != totalApplesStr.rend(); ++it) {
    /* Do whatever you need to */
}

使用std :: string代替char數組。

然后,您可以使用std :: tranform轉換為int向量來進行大數計算。

您嘗試從尚未初始化的數組中測試值。

盡管char數組是可用於此目的的不安全的方法,但可以使用初始化程序對其進行修復:

char totalapples[102] = {0};

同樣,您的第二個循環將向后打印結果。 嘗試遞增 i 而不是遞減i

您新初始化了計數器/索引。 還有許多其他改進要做,但是您的代碼很短

#define ARRAY_SIZE 102

int main {
    char totalapples[ARRAY_SIZE];
    unsigned int i = ARRAY_SIZE;
    i = 0;
    while (i < ARRAY_SIZE)
    {
        cin>>totalapples[i]; // range is 0..101
        i++;
    }    

    i = ARRAY_SIZE;
    while (i > 0)
    {
        cout<<totalapples[i]; // range is 0..101
        i--; 
    }   
}

暫無
暫無

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

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