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

问题描述 投票:0回答:1

Hello Stack溢出社区!

我目前在使用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

它存储在位置为D:\ Maze.txt的外部USB上,当前,当我在运行时检查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++ file fstream ifstream
1个回答
0
投票

您的代码有两个主要问题。

首先,当您将Windows路径写入C ++中的文件时,您要使用双反斜杠,如下所示:inFile.open("D:\\Maze.txt");,因为单反斜杠是C ++字符串中的转义字符,因此,如果要在字符串中使用反斜杠,则可以必须先使用反斜杠将其转义。

[第二件事是,当您检查打开文件的操作是否失败时,您不希望仅打印错误并继续对未正确初始化的inFile变量执行命令。因此,在打开和处理文件时,如果inFile.fail()为true,则应使用“ try-catch块”,停止程序或从函数返回。因此,最简单的方法是将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();
}
© www.soinside.com 2019 - 2024. All rights reserved.