简体   繁体   中英

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

I have to write a c++ programm with QtCreator to evaluate a football table. The results of every game is saved in a text file ("Bundesliga.txt"). We have to use fstream to read the file, but I can't open it. 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. Nothing worked. I'm glad for evey single help!

Edit:

I'm using Qt-Creator.

Pay attention to the following:

  1. The .txt file must be within the source code file's folder.
  2. Check that your file name as you see it in the folder isn't Bundesliaga.txt , it's interpreted to Bundesliga.txt.txt . This is a common mistake.
  3. Ask if(!table.is_open())
  4. You're not nulling the string with \\0 . Do that or use table >> setw(10) . setw is declared at <iomanip> and nulls the string with \\0 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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