从文件中读取 C++ 不起作用

c++ reading from a file does not work

本文关键字:C++ 不起作用 读取 文件      更新时间:2023-10-16

我试图从文件中读取,基本上我的文本文件是这样的;

23 4 * 19 2 - + #
6 3 -  #
36 #

我试图通过忽略文件末尾的#从文件中读取它们。我不想接受#.之后,我想将其存储在我的队列中。这是我的代码的一部分,如下所示;当我显示我的队列时,它仍然需要#。我不知道为什么。如果你帮助我,我会很高兴

while (!myFile.eof()) {
        getline(myFile, a, ' ');
        if (a != str4) {
            q.enqueue(a);
        }
        else {
            cout << " " << endl;
        }
    }
    q.display(cout);

一个简单的方法是将文本行读入字符串。 接下来找到#符号并擦除#之后字符串中的所有字符。

std::string test_string = "help fred # not fred.n";
const std::string::size_type position = test_string.find_first("#");
test_string.erase(position, test_string.length() - position);
std::cout << "After truncation, string is: " << test_string << "n";

您可以使用正则表达式清理数据:

    std::smatch _match;
    std::regex line_regex("(.*)#");
    string line;
    while(getline(myfile,line))
    {
        std::regex_search(line, _match, line_regex);
        if (_match.size() > 0)
        {
            cout << _match[1].str() + "n";
        }
    }

正则表达式将忽略 # 之后的任何内容。根据文件的示例内容,输出将是

输入内容:

23 4 * 19 2 - + #
6 3 -  # 23244
36 #

输出:

23 4 * 19 2 - + 
6 3 -  
36