【问题标题】:Getting multiple inputs from one line from a file in c++从c ++中的文件中的一行获取多个输入
【发布时间】: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 有些主题是多个单词
  • 我的建议是您首先将整行读入一个字符串。然后尝试解析字符串。这通常更容易(而且更不容易出错)。
  • 我解决了这个问题,谢谢大家的意见!

标签: c++ string file-io


【解决方案1】:

您可以使用一个虚拟字符变量来“拾取”$ 字符:

char dummy_char;
infile >> subject >> dummy_char >> biologyscores[0] >> biologyscores [1];  //read into string and int array

【讨论】:

  • 这适用于这个输入,谢谢。不过我很好奇,如何让它与多个单词的主题一起工作? IE。计算机科学
  • 如果$总是出现,你可以用它作为主语的终止符,不管是一个词还是多个。
【解决方案2】:

您可以使用 seekgtellg

    std::fstream infile("myScores.txt"); //declare infile to read from "myScores.txt"
int temp;
infile >> subject;   //read into string 
temp=infile.tellg(); //to get the position of $
infile.seekg(temp+1);// to move one step forward 
infile>> biologyscores[0] >> biologyscores [1];//now you can read the int values

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多