輸入不定長度的數(shù)組

某些算法題的輸入沒有要求輸入長度,而是直接輸入長度未知的數(shù)組

下面講講如何方便地輸入不定長度的數(shù)組:

  1. 我在一次筆試中第一次遇到這種輸入數(shù)組的方式,當(dāng)時(shí)想的比較復(fù)雜,直接是按照字符串輸入,然后處理字符串,將數(shù)組賦值。
#include <iostream>
using namespace std;
int main()
{
    string str;
    int nums[5000] = {0};
    getline(cin, str);
    int i, count = 0;
    for (i = 0; i<= str.length(); i++) {
        if (str[i] == ' ' || str[i] == '\0') {
            int j = i-1;
            int plus = 1;
            while (j >= 0) {
                if (str[j] == '-') { //是負(fù)數(shù)
                    nums[count] *= -1;
                    count++;
                    break;
                }
                if (str[j] <= '9' && str[j] >= '0') {
                    nums[count] += plus * (str[j] - '0');
                    plus *= 10;
                    j--;
                    if (j < 0) count++; //算上第一個(gè)數(shù)
                } else {
                    count++;
                    break;
                }
            }
        }
    }
    for (i = 0; i < count; i++) {
        cout<<nums[i]<<" ";
    }
    cout<<endl;
}
  1. 然而筆試后我上網(wǎng)看了一下網(wǎng)友的分享,發(fā)現(xiàn)了更簡(jiǎn)單的用法:
#include <stdio.h>
int main(){
    int num;
    int i = 0, count = 0;
    int arr[10];
    while(1){
        scanf("%d", &num);
        count++;
        char c = getchar();
        arr[i++] = num;
        if(c == '\n'){ //監(jiān)測(cè)到回車
            break;
        }
    }
    for (i = 0; i < count; i++) {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容