在ACM模式中,常会遇到输入每行具有特定分隔符的多行 输入格式: abc.txt
22,2,3,4,5,6,67,68,69,70,71
12,22,23,24,25,26,27,29,32
32,33,34,35,36
C方式
#include <cstdio>
#include <cstring>
int main() {
freopen("abc.txt", "r", stdin);
char buff[1024];
const char*p = NULL;
char splitchar = ',';
while(gets(buff)) {
p = buff;
while(sscanf(p, "%d", &val) != EOF)
{
printf("%d ", val);
p = strchr(p, splitchar);
if (p != NULL)
p++;
}
printf("\n");
}
}
C++方式
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <fstream>
#include <cstdio>
using namespace std;
int main() {
string line;
int val;
vector<vector<int>> arr;
freopen("abc.txt", "r", stdin);
while (getline(cin, line)) {
stringstream ss(line);
vector<int> vec;
while(ss >> val)
{
vec.push_back(val);
ss.ignore();
}
arr.push_back(vec);
}
for (int i = 0; i < arr.size(); ++i) {
for (int j = 0; j < arr[i].size(); ++j) {
cout << arr[i][j] << ' ';
}
cout << endl;
}
}
|