当前位置: 代码迷 >> 综合 >> 机试输入读取技巧(持续更新中)
  详细解决方案

机试输入读取技巧(持续更新中)

热度:49   发布时间:2023-09-24 04:27:50.0

情况1

输入:
1 2 3
3 6 5 2 5
7 7 55
1

如上可看出输入每一行的数字个数是未知的,需求是,每一行的数据为一个处理单元。

方法:利用stringstream将getline读取的一行数据,重新将行中的数据赋值给对应类型的变量。省去了删去空格与类型转换的操作。如果输入为string,例如:可以将下方的int改为string.

输入:
ac bc dd
apple pear banana
merry christmas
#include <cstdio>
#include <iostream>
#include <cstring>
#include <sstream>
#include <string>
using namespace std;int main(){//获取控制台端输入//每一行为一个输入单元string str;int num;while (getline(cin, str)){stringstream ss(str);int num;while (ss >> num){cout << num << ' ';}cout << endl;}return 0;
}

 

  相关解决方案