无法连续读取两个不同的文件

Unable to read two different files in succession

本文关键字:两个 文件 连续 读取      更新时间:2023-10-16

我正在编写一个程序,它可以接受3个命令,command1、command2和bye。前两个命令应该读取一个文件并对这些文件中的数据执行某些操作。

现在的问题是。。它无法连续处理两个不同的文件。例如

command1 testing.txt
... THIS WORKS ...
command1 testingagain.txt
wrong command! try again!

我希望每次使用任何文件名输入命令时,命令都能正常工作。我不确定如何更改代码的结构来实现这一点。

while (getline(cin, str1)){
        if (str1 == "bye")
        {
            return 0;
        } else {
            s1.str (str1);
            s1 >> command;
            s1 >> filename;
            ifs.open(filename.c_str()); 
            if (ifs.fail()) {                                                       
                cerr << "ERROR: Failed to open file " << filename << endl;   
                ifs.clear();   
            } else { 
                if (str1 == "command1 " + filename) {
                    command1(filename);
                } else if (str1 == "command2 " + filename) {
                    command2(filename);                                                              
                }   else {
                    cout << "Wrong command! try again!" << endl;
                } 
            }
            ifs.close();
        }
    }
    return 0;

s1.str (str1);无法按预期工作。每次都应该创建新的istringstream对象:

istringstream s1(str);
s1 >> command;
s1 >> filename;

或在str():之后添加clear()

s1.str(str);
s1.clear();
s1 >> command;
s1 >> filename;