c ++嵌套while循环仅运行一次

c++ nested while loop runs only once

请指教,为什么内循环只运行一次? 我想为输入文件的每一行添加后缀,然后将结果存储在输出文件中。

谢谢

例如: 输入文件包含:

AA
AB
AC

后缀文件包含:

_1
_2

输出文件应包含:

AA_1
AB_1
AC_1
AA_2
AB_2
AC_2

我的结果是:

AA_1
AB_1
AC_1

代码:

int main()
{
    string line_in{};
    string line_suf{};
    string line_out{};
    ifstream inFile{};
    ofstream outFile{"outfile.txt"};
    ifstream suffix{};

    inFile.open("combined_test.txt");
    suffix.open("suffixes.txt");

    if (!inFile.is_open() && !suffix.is_open()) {
        perror("Error open");
        exit(EXIT_FAILURE);
    }

    while (getline(suffix, line_suf)) {
        while (getline(inFile, line_in))
        {
            line_out = line_in + line_suf;
            outFile << line_out << endl;
        }
        inFile.close();
        outFile.close();
    }

}

恕我直言,更好 的方法是将文件读入 vectors,然后遍历向量:

std::ifstream word_base_file("combined_test.txt");
std::ifstream suffix_file("suffixes.txt");
//...
std::vector<string> words;
std::vector<string> suffixes;
std::string text;
while (std::getline(word_base_file, text))
{
    words.push_back(text);
}
while (std::getline(suffix_file, text))
{
    suffixes.push_back(text);
}
//...
const unsigned int quantity_words(words.size());
const unsigned int quantity_suffixes(suffixes.size());
for (unsigned int i = 0u; i < quantity_words; ++i)
{
    for (unsigned int j = 0; j < quantity_suffixes; ++j)
    {
        std::cout << words[i] << suffix[j] << "\n";
    }
}

编辑 1:无向量
如果您还没有了解矢量或喜欢破坏您的存储设备,您可以试试这个:

std::string word_base;
while (std::getline(inFile, word_base))
{
    std::string  suffix_text;
    while (std::getline(suffixes, suffix_text))
    {
        std::cout << word_base << suffix_text << "\n";
    }
    suffixes.clear();  // Clear the EOF condition
    suffixes.seekg(0);  // Seek to the start of the file (rewind).
}

记住,在内部 while 循环之后,suffixes 文件在最后;不会再发生读取。因此,文件需要在读取之前定位在开头。另外,读取前需要清除EOF状态。