如何利用 fstream 从 .txt 文件 C++ 中取出 int 值

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

你好 Stack Overflow 社区!

我目前在使用 ifstream 从 .txt 文件中取出两个 int 值时遇到问题。我的最终目标是将前两个值 [6] [4] 作为两个整数,称为 xSizeySize

文件内容为;

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

它存储在外部 USB 上,位置为 D:\Maze.txt,目前,当我在运行时检查 int 的值时,xSize 值变为 0,而 ySize 没有改变。

如有任何帮助,我们将不胜感激!

谢谢!!!!!

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();
}

您的代码存在两个主要问题。

首先,当您在 C++ 中编写文件的 Windows 路径时,您希望像这样使用双反斜杠:inFile.open("D:\Maze.txt");,因为单反斜杠在 C++ 字符串中是转义字符,因此如果你想要在字符串中使用反斜杠,你必须先用反斜杠对其进行转义。

第二件事是,当您检查文件打开是否失败时,您不希望只打印出错误并继续对未正确初始化的 inFile 变量执行命令。因此,您应该在打开和使用文件时使用 "try-catch block",如果 inFile.fail() 为真,则在这种情况下停止程序或从函数中使用 return。最简单的方法就是将 return; 放在 if 语句块中。

在此之后,如果 "Maze.txt" 文件存在,并且文件路径正确,您的代码应该可以运行。它对我有用。

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();
}