C++多行输入不定个数数字

C++多行输入不定个数数字

引言

今天在做一个线上笔试的时候,碰到了一个让我觉得很有必要重视的关于C++输入的问题。通常我们处理一个数组的输入都会在知道数组大小的前提下进行。输入数据的个数未知的情况一般也出现在多行输入中每行输入的个数已知,输入次数(即到底有多少行)未知的情况。所以今天我碰到的是一个两行的数组输入,不过每行的个数未知的情况。在我的个人习惯下,遇到多个数的输入时,不愿意用字符的形式去读取它们,可最后想想,发现这个情况只能以字符串的形式来处理才行,所以在此整理了一下,当输入一行或多行以空格(单个或多个空格)隔开的数组,如何正确的读入。

目标

输入示例

1 2 5 7 12 23
4 5 8 10

每行的数个数不定

代码

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;

int stringline_to_array(string& A, int *a) {
  int i=0,count=0,fore=0;
  while(A[i]==' ') {                                   //忽略每行开头空格
    fore++;
    i++;
  }
  while (i!=A.length()) {
    if (A[i]==' ') {
      a[count] = stoi(A.substr(fore, i-fore));         //截取连续的一段非空字符转为数字
      count++;
      fore=i;
      while(A[i]==' ') {                               //忽略间隔空格
        fore++;
        i++;
      }
    } else if (i==A.length()-1 && A[i]!=' ') {         //保存末尾非空字符
      string temp = A.substr(fore);
      a[count] = stoi(temp);
      count++;
      i++;
    } else {
      i++;
    }
  }
  return count;                                        //返回数组长度
}

int main()
{
  int a[10];
  int b[10];
  string A,B;
  getline(cin, A);
  getline(cin, B);
  int counta;
  int countb;
  counta=stringline_to_array(A, a);
  countb=stringline_to_array(B, b);
  for (int i=0; i<counta; i++)
    cout << a[i] << " ";
  cout << endl;
  for (int i=0; i<countb; i++)
    cout << b[i] << " ";
  cout << endl;
  return 0;
}

运行

输入

1 2 3 5 11 18
5 6 7

输出

1 2 3 5 11 18
5 6 7

后续

当然,这里的情景是每行输入有个较小的限定范围,如果范围限定比较大的话,建议将main函数中的数组a,b换成vector实现

#include<iostream>
#include<stdlib.h>
#include<string>
using namespace std;

int stringline_to_array(string& A, int *a) {
  int i=0,count=0,fore=0;
  while(A[i]==' ') {
    fore++;
    i++;
  }
  while (i!=A.length()) {
    if (A[i]==' ') {
      a.push_back(stoi(A.substr(fore, i-fore)));      //修改这里
      count++;
      fore=i;
      while(A[i]==' ') {
        fore++;
        i++;
      }
    } else if (i==A.length()-1 && A[i]!=' ') {
      string temp = A.substr(fore);
      a.push_back(stoi(temp));                        //和这里
      count++;
      i++;
    } else {
      i++;
    }
  }
  return count;
}

int main()
{
  vector<int> a;                                      //vector的应用场景更普遍
  string A;
  getline(cin, A);
  int counta;
  counta=stringline_to_array(A, a);
  for (int i=0; i<counta; i++)
    cout << a[i] << " ";
  cout << endl;
  return 0;
}
  • 5
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值