为什么 getline() 不从文件中读取任何内容?

Why Does getline() Doesn't Read anything from a file?

我编写了一个代码,它接受一个 txt 文件作为输入,然后进行解析,并将它们放入二维数组 myarray[][2] 中。 输入文件结构如下所示:

aaa/bbb
bbb/ccc
ccc/ddd

并且应该这样解析:

myarray[0][0] = "aaa"
myarray[0][1] = "bbb"
myarray[1][0] = "bbb"
myarray[1][1] = "ccc"

我为此编写的代码:

void Parse_File(string file){
    ifstream inFile;
    inFile.open(file);
    if (inFile.is_open()){
        inFile.clear();
        int lines = count(istreambuf_iterator<char>(inFile), istreambuf_iterator<char>(), '\n');
        string myarray[lines][2];
        int mycount = 0;
        do{
            getline(inFile, input);
            myarray[mycount][0] = input.substr(0, input.find("/"));
            myarray[mycount][1] = input.substr(input.find("/") +1, input.length());
            mycount++;
        }while (input != "");
    }else{
        Fatal_Err("File Doesn't Exist");
    }
    inFile.close();
}

但是在这个函数之后,myarray 中没有任何内容。 do-while 语句不会循环。我不知道为什么。任何帮助表示赞赏。谢谢

移动“getline(inFile, input);”到循环的末尾并在进入之前再次调用它。在您进入循环之前输入可能是“”,因此永远不会调用循环并且永远不会更新输入。

您的文件有一些问题,但最主要的是:您忘记将文件阅读指针返回到文本文档的开头。 count 函数将上述指针指向末尾,因此您需要将其取回。

所以您需要使用 seekg() 功能将指针拖动到任何您想要的地方。

看看下面的代码是否适合您

void Parse_File(string file)
{
    ifstream inFile;
    inFile.open(file);
    if (inFile.is_open())
    {
        inFile.clear();
        int lines = count(istreambuf_iterator<char>(inFile), istreambuf_iterator<char>(), '\n');
        //Pitfall : By counting the lines, you have reached the end of the file.
        inFile.seekg(0);// Pitfall solved: I have now taken the pointer back to the beginning of the file.
        ....
        ....//Rest of your code
    }
}

此外,您需要学习调试,以便更容易理解您的代码。我会推荐 visual studio code for debugging c++.