c++ 输入一行以空格分割的数字(数目未知),存入整型数组

27 篇文章 2 订阅

方法一:

利用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;
    }
}

在这里插入图片描述

方法二:

#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;
    }
}

在这里插入图片描述

方法三: 一行中输入多个字符串并以空格间格,通过多个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;
}

输出的其实是字符串的形式
在这里插入图片描述

#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;
    }
}

在这里插入图片描述

方法四:

#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;
}

在这里插入图片描述

  • 23
    点赞
  • 74
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值