首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从c++中的文件中从一行获取多个输入

从c++中的文件中从一行获取多个输入
EN

Stack Overflow用户
提问于 2021-12-03 20:23:16
回答 2查看 582关注 0票数 0

基本上,我试图从一行代码中获得三种东西,即从.txt文件中读取。这将被重复,但现在我只需要知道如何得到一行。我读到的台词是这样的:

代码语言:javascript
复制
Biology                 $11 12

所以我想要一个字符串和两个in,完全忽略$(注意,我不能更改.txt文件,所以我必须保留$ in)

所以如果我有

代码语言:javascript
复制
string subject;
int biologyscores[25];

我的代码是:

代码语言:javascript
复制
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

因此,字符串将被用来检查这些分数是为了哪个主题,而分数本身将存储在一个数组生物分数中,它们彼此索引。

问题是,在执行这段代码之后,subject =“生物学”是理想的,但指数0和1的生物分数似乎都有垃圾数,而不是我想要读到的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-12-03 20:29:14

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

代码语言:javascript
复制
char dummy_char;
infile >> subject >> dummy_char >> biologyscores[0] >> biologyscores [1];  //read into string and int array
票数 0
EN

Stack Overflow用户

发布于 2021-12-03 21:36:24

您可以使用seekgtellg

代码语言:javascript
复制
    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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70220263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档