【发布时间】:2022-01-10 04:09:09
【问题描述】:
基本上,我试图从一行代码中获取三件事,从 .txt 文件中读取。这将重复,但现在我只需要知道如何获得一条线。我正在阅读的行如下所示:
Biology $11 12
所以我想得到一个字符串和两个整数,并完全忽略 $(注意,我无法更改 .txt 文件,所以我必须保留 $)
如果我有
string subject;
int biologyscores[25];
我的代码是:
int biologyscores[25]; //array to store the integer values
std::string subject; //string to store the subject the scores are for
std::ifstream infile("myScores.txt"); //declare infile to read from "myScores.txt"
infile >> subject >> biologyscores[0] >> biologyscores [1]; //read into string and int array
因此字符串将用于检查这些分数是针对哪个科目的,并且分数本身将存储在一个数组 bioscores 中,彼此相邻索引。
问题是在这段代码执行之后,需要的 subject = "Biology",但索引 0 和 1 的 bioscores 似乎都有垃圾数字,而不是我想要读入的数字。
【问题讨论】:
-
根据您的文件格式,您可能希望将整行读入 std::string 并解析字符串。还要小心阅读带有
nfile >> subject的字符串,您的所有主题都正好是 1 个单词,并且没有机会在其中包含空格字符? -
@drescherjm 有些主题是多个单词
-
我的建议是您首先将整行读入一个字符串。然后尝试解析字符串。这通常更容易(而且更不容易出错)。
-
我解决了这个问题,谢谢大家的意见!