简体   繁体   中英

How can I utilise fstream to take out int values from a .txt file C++

Hello Stack Overflow Community!

I'm currently having trouble using ifstream to take out two int values from a.txt file. My end goal is to have the first two values [6] [4] as two integers called xSize and ySize .

The file's contents are;

6 4 0 0 1 0 0 0 2 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 3 0

it's stored on an external USB with the location D:\Maze.txt and currently, when I check the value of the int at runtime the xSize value gets changed to 0 and the ySize doesn't change.

Any help on this would be massively appreciated!

Thank you!!!!!

void imp()
{
    //Test Case
    //6 4 0 0 1 0 0 0 2 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 3 0 0 0 0 0 3

    int xSize; //Size of X Col
    int ySize; //Size of Y Col

    std::cout << "Import Begins\n" << std::endl;

    std::ifstream inFile;

    inFile.open("D:\Maze.txt");

    //Error Checker 
    if (inFile.fail()) 
    {
        std::cout << "Error importing file.";
    }

    //Import Complete now to fill our vaulues 

    inFile >> xSize >> ySize;

    inFile.close();
}

There are two major issues with your code.

First of all when you are writing Windows path to the file in C++ you want to use double backslash like this: inFile.open("D:\\Maze.txt"); , because single backslash is escape character in C++ string, therefore if you want a backslash inside of the string you have to escape it with backslash first.

Second thing is when you check if opening of the file failed you don't want just to print out error and continue executing commands on the inFile variable which is not initialized properly. Hence, you should use "try-catch block" when opening and working with file, stop the program or return from the function in this case if inFile.fail() is true. So easiest is to just put return; in the if statement block.

After this, if "Maze.txt" file exists, and if the file path is correct your code should work. It worked for me.

void imp()
{
    //Test Case
    //6 4 0 0 1 0 0 0 2 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 3 0 0 0 0 0 3

    int xSize; //Size of X Col
    int ySize; //Size of Y Col

    std::cout << "Import Begins\n" << std::endl;

    std::ifstream inFile;

    inFile.open("D:\\Maze.txt");

    //Error Checker 
    if (inFile.fail()) 
    {
        std::cout << "Error importing file.";
        return;
    }

    //Import Complete now to fill our vaulues 

    inFile >> xSize >> ySize;

    inFile.close();
}

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