C++没有从文本文件中将值读入数组

C++ Not reading in values into array from text file

本文关键字:数组 文件 文本 C++      更新时间:2023-10-16

我一直试图将文本文件中的值读入两个数组,但最终在namesscores数组中一无所获。这是我的:

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

6
Alice 50
Bob 100
Cathryn 75
Don 90
Emily 80
Flora 60
George 95

name正在获取值6,但namesscores没有获取任何值。有什么问题吗?

您的程序无法运行,因为您意外地将names初始化为数组类型int,而不是类型std::string。这会破坏整个线路inputFile >> names[x] >> scores[x];

愚蠢的错误。只需制作一个名为namesstd::strings的数据结构并在其中放入内容即可。