使用fstream和sstream一起从文件中分离字符串/整数
Use fstream and sstream together to separate strings/integers from file
所以我想从文件中获取信息,它将从名称(字符串)开始,最终将更改为整数。
交货。对于nums.txt
James Smith
John Jones
Amy Li
1 3 2 3
3 2 4 1 0
我想写一个程序来存储每个名字(每行一个名字),然后当名字结束,数字开始时,它开始将每个#添加到数组中。例如,如果出现了3个2,我想要
numInt[2] to equal 3
我想使用ifstream从文件中获取输入,并使用stringstream对字符串和整数进行排序。到目前为止我有这个
int main() {
string names[10];
int numNames = 0;
int numInt[100] = {};
ifstream file("nums.txt");
stringstream ss;
string s;
int n;
while (file >> ss) {
while (ss >> s) {
names[numNames] = s;
numNames++;
}
while (ss >> n) {
numInt[n]++;
}
}
return 0;
}
我知道我做错了,但我不确定如何正确地做这件事。
我想我会这样做:
while (file >> ss) {
if (isalpha((unsigned char)ss[0])
names.push_back(ss);
else {
std::istringstream buf(ss);
int n;
while (buf >> n)
numbers.push_back(n);
}
}
这支持你所要求的,但不严格执行它。那么,如果您有这样的内容:
Joe Blow
1 2 3
Jerry Coffin
…它将把Joe Blow和Jerry Coffin放在names
和1
中,2
和3
放在numbers
中。