gpt4 book ai didi

c++ - 一起使用 fstream 和 sstream 从文件中分离字符串/整数

转载 作者:搜寻专家 更新时间:2023-10-31 02:22:06 24 4
gpt4 key购买 nike

所以我想从文件中获取信息,它将以名称(字符串)开头,最终将变为整数。

例。对于 nums.txt

James Smith
John Jones
Amy Li
1 3 2 3
3 2 4 1 0

我想编写一个程序来存储每个名称(每行一个名称),然后当名称结束和数字开始时,它开始将每个 # 出现添加到数组中。IE。如果出现 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);
}
}

这支持您的要求,但并不严格执行。 IOW,如果你有类似的东西:

Joe Blow
1 2 3
Jerry Coffin

...它会将“Joe Blow”和“Jerry Coffin”放入names12 3numbers 中。

关于c++ - 一起使用 fstream 和 sstream 从文件中分离字符串/整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com