如何在 c++ 中使用 fstream 读取.txt文件

How do I read .txt files with fstream in c++

本文关键字:fstream 读取 txt 文件 c++      更新时间:2023-10-16

我必须用QtCreator编写一个c++程序来评估足球表。每场比赛的结果都保存在一个文本文件中("德甲.txt"(。我们必须使用 fstream 来读取文件,但我无法打开它。 这是我读取文件的测试程序。

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
char test[10];
ifstream table;
table.open("Bundesliga.txt");
if (table.fail())
{
cerr << "Error Opening File n";
exit(1);
}
table.getline(test, 10);
cout << test;
return 0;
}

文本文件保存在项目文件夹中,我将该文件导入为资源和OTHER_FILES。什么都没用。我很高兴有单一的帮助!

编辑:

我正在使用Qt-Creator。

注意以下几点:

  1. .txt文件必须位于源代码文件的文件夹中。
  2. 检查您在文件夹中看到的文件名是否Bundesliaga.txt,它被解释为Bundesliga.txt.txt。这是一个常见的错误。
  3. if(!table.is_open())
  4. 您不会用清空字符串。这样做或使用table >> setw(10)。setw 在<iomanip>处声明,并使用为空字符串。