天天看點

c++ 輸入一行以空格分割的數字(數目未知),存入整型數組

方法一:

利用getchar函數和ungetc函數,通過getchar函數判斷回車,以及判斷時候為數字,然後通過ungetc函數,将通過getchar函數獲得的字元送回緩沖區,再通過cin函數取出作為int型數組。

#include<iostream>
using namespace std;
int main()
{
    int a[50];
    int i = 0;
    char c;
    while((c=getchar())!='\n')
    {
        if(c!=' ')//把這句判斷條件改動
        {
            ungetc(c,stdin);
    //如果字元c不是空格,就要将c字元還回到流中,不然造成資料讀取錯誤
            cin>>a[i++];
    //流輸入會将第一個資料全讀入,直到遇到空格
        }
    }
    for(int j=0;j<i;j++)
    {
        cout<<"a["<<j<<"]:"<<a[j]<<endl;
    }
}
           
c++ 輸入一行以空格分割的數字(數目未知),存入整型數組

方法二:

#include<iostream>
using namespace std;
 
int main()
{
    int a[20];
    int i = 0;
    char c;
    cin>>a[i++];
    while((c=getchar())!='\n')
    {
        cin>>a[i++];
    }
    for(int j=0;j<i;j++)
    {
        cout<<"a["<<j<<"]:"<<a[j]<<endl;
    }
}
           
c++ 輸入一行以空格分割的數字(數目未知),存入整型數組

方法三: 一行中輸入多個字元串并以空格間格,通過多個string存儲

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int main(){
    string str;
    string arr[100];
    int index = 0;
    while(cin>>str){//string遇到空格會停止
        arr[index++] = str;
        char ch = getchar();//通過getchar()來判斷最後輸入回車符結束
        if(ch == '\n') break;
    }

    for(int i=0;i<index;i++)
        cout<<arr[i]<<" ";
    cout<<endl;
    return 0;
}
           

輸出的其實是字元串的形式

c++ 輸入一行以空格分割的數字(數目未知),存入整型數組
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
    int a[50];
    int i = 0;
    char c;
    string str = "";
    while((c=getchar())!='\n')
    {
        //if(c>='0'&&c<='9')
        if(c != ' ')
        {
            str += c;
        }
        else if(c ==' ')
        {
            a[i++] = atoi(str.c_str());
            str = "";
        }
    }
    a[i++] = atoi(str.c_str());
    for(int j=0;j<i;j++)
    {
        cout<<"a["<<j<<"]:"<<a[j]<<endl;
    }
}
           
c++ 輸入一行以空格分割的數字(數目未知),存入整型數組

方法四:

#include<iostream>
#include<string>
#include<sstream>
using namespace  std;
int main()
{
    string  word;
    string str;
    getline(cin,str);

    stringstream ss(str);
    int a;
    while (ss >> word){
        cout<< word<<endl;
        a = stoi(word);
        cout<< a << endl;
    }

    return 0;
}
           
c++ 輸入一行以空格分割的數字(數目未知),存入整型數組