[英]C++ Not reading in values into array from text file
I've been trying to read in values from a text file into 2 arrays, however I end up with nothing inside my names
and scores
arrays. 我一直试图将文本文件中的值读入2个数组中,但是最终我的names
和scores
数组中什么都没有。 Here's what I have: 这是我所拥有的:
const int size = 6;
int names[size] = { 0 };
int scores[size] = { 0 };
int name;
ifstream inputFile;
inputFile.open("input.txt"); //opens up textfile
inputFile >> name;
while (!inputFile.eof()){
inputFile >> names[x] >> scores[x];
cout << names[x] << scores[x];
x++;
}
input.txt input.txt
6
Alice 50
Bob 100
Cathryn 75
Don 90
Emily 80
Flora 60
George 95
name
is picking up a value of 6, but names
and scores
are picking up nothing. name
的取值为6,但names
和scores
的取值为1。 Any ideas about what's wrong? 有什么问题的想法吗?
You're program doesn't work because you accidentally initialized names
as an array type int
, instead of type std::string
. 您的程序无法正常工作,因为您不小心将names
初始化为数组类型int
,而不是类型std::string
。 This breaks the whole line inputFile >> names[x] >> scores[x];
这会破坏整行inputFile >> names[x] >> scores[x];
. 。
Silly mistake. 愚蠢的错误。 Just make a data structure of std::string
s called names
and put stuff in it. 只是做的数据结构std::string
叫做names
,并把东西在里面。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.