简体   繁体   English

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

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

I have to write a c++ programm with QtCreator to evaluate a football table. 我必须用QtCreator编写一个c ++程序来评估足球桌。 The results of every game is saved in a text file ("Bundesliga.txt"). 每个游戏的结果都保存在一个文本文件(“ Bundesliga.txt”)中。 We have to use fstream to read the file, but I can't open it. 我们必须使用fstream读取文件,但无法打开它。 Here is my test programm to read the file. 这是我读取文件的测试程序。

#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;
}

The textfile is saved in the project folder and I imported the file as RESOURCES and OTHER_FILES. 文本文件保存在项目文件夹中,我将其导入为RESOURCES和OTHER_FILES。 Nothing worked. 没事。 I'm glad for evey single help! 我很高兴能提供单一帮助!

Edit: 编辑:

I'm using Qt-Creator. 我正在使用Qt-Creator。

Pay attention to the following: 请注意以下几点:

  1. The .txt file must be within the source code file's folder. .txt文件必须位于源代码文件的文件夹中。
  2. Check that your file name as you see it in the folder isn't Bundesliaga.txt , it's interpreted to Bundesliga.txt.txt . 检查您在文件夹中看到的文件名不是Bundesliaga.txt ,它被解释为Bundesliga.txt.txt This is a common mistake. 这是一个常见的错误。
  3. Ask if(!table.is_open()) 询问if(!table.is_open())
  4. You're not nulling the string with \\0 . 您不会用\\0使字符串无效。 Do that or use table >> setw(10) . 这样做或使用table >> setw(10) setw is declared at <iomanip> and nulls the string with \\0 . setw在<iomanip>处声明,并将字符串以\\0 <iomanip>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM