我们的教授给了我们这个作业,我们有一个 .txt
文件,格式如下:
John 23
Mary 56
Kyle 99
Gary 100
...etc. etc.
我们要做的是读取文件,并将名称和分数存储在并行数组中。
事实证明,这对我来说比我预期的更具挑战性。在搜索堆栈时,让我感到困惑的是人们用来执行此操作的所有不同库。我们的教授只是希望我们使用 string
、fstream
和 sstream
来执行此操作。
下面是我到目前为止的想法,它编译完美,将分数与名称分开,但将它们存储在同一个数组中:
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int SIZE = 50;
string names[SIZE];
int score [SIZE];
short loop = 0;
string line;
ifstream inFile("winners.txt");
if (inFile.is_open())
{
while(!inFile.eof())
{
istream& getline(inFile >> line);
names[loop] = line;
cout << names[loop] << endl;
loop++;
}
inFile.close();
}
else cout << "Can't open the file" << endl;
return 0;
}
我不是在找人来解决我的硬件问题,我只是想朝着正确的方向前进!
最佳答案
如果您想为每行输入读取两个内容,那么使用两个“读取”语句似乎是合理的:
std::string name;
inFile >> name;
int score;
inFile >> score;
std::cout << "Read score " << score << " for name " << name << '\n';
...然后您可以重复执行此操作,直到您阅读了整个文件。
编辑:在您确定基本逻辑后,您可能需要考虑错误处理。例如,如果输入文件不包含 50 对 (name, score),您的程序的适当行为是什么?您如何更改代码以获得该行为?
关于c++ - 从 .txt 文件中提取行,然后将单词存储到单独的数组中 | C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10668212/