天天看点

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++ 输入一行以空格分割的数字(数目未知),存入整型数组