ACM -C++输入

将不确定行数的字符转换为二维数值数组

代码

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
//另外推荐一个  万能头文件#include“bits/stdc++.h” 如果引入这个 上面的都可以不用写
using namespace std;

int main()
{
  string str;
  vector<int> res;
  vector<vector<int>> result;
  while (cin >> str) //不断输入数字字符 逗号分隔  回车换行 
  {
    stringstream ss; 
    ss << str; //为了使用 getline()这个函数
    string tmp;
    while (getline(ss, tmp, ',')) //分割一行字符
    {
      res.push_back(stoi(tmp)); 
    }

    result.push_back(res);//等到一行字符都被分割完毕以后 ,得到完整的res, 再压入二维数组reslult
    res.clear();
  }

  for (auto it = result.begin(); it != result.end(); it++) //二维数组遍历
  {
    for (auto it1 = (*it).begin(); it1 != (*it).end(); it1++)
    {
      cout << *it1 << " ";
    }
    cout << endl;
  }

  return 0;
}

例子

在这里插入图片描述
输入带逗号的数字 我们称之为字符
通过 ctrl + z 停止输入
最终输出为打印 二维数组

将不确定行数的整数转换为二维数组

代码

 #include <bits/stdc++.h>
 using namespace std;
 
 int main (int argc , char ** argv)
 { 

   int n;
   cin >>n; //一行n个元素
   vector<int> v1(n);
   vector<vector<int>> v2;
   while(cin)
   {
      for (int j = 0; j <n ; j++)
      {
         cin >> v1[j];
      }

      v2.push_back(v1); //最后存入二位数组里边
      v1.clear();
   }   
   v2.pop_back();

   for (auto s : v2) //二维数组遍历
   {
      for (auto s1 :s)
      {
         cout << s1 << " "; 
      }
      cout <<endl;
   }

 }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值