繁体   English   中英

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();
    }

}

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

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 状态。

让我试试看我的水晶球是如何工作的。 (问题的编辑确认我的水晶球非常清晰)

while we can read from the suffix stream.
    read one line from inFile
        do some stuff
    close inFile. inFile will no longer be read.

我猜你在问题中输入的格式是否关闭,即它实际上是(如果不使用 (suffix >> line_suffix) 作为条件)。

_1
_2

您过早地关闭inFile

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM