【问题标题】:c++ nested while loop runs only oncec++嵌套while循环只运行一次
【发布时间】:2021-12-17 07:37:30
【问题描述】:

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

谢谢

例如: 输入文件包含:

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

}

【问题讨论】:

  • getline(inFile, line_in) 应该读多少次换行?
  • 如果inFile 在外循环的第一次迭代结束时关闭,那么下一次迭代有什么要读的?使用seekg 倒带文件似乎是一个更好的主意。
  • @Drew Dormann - getline(inFile, line_in) 应该读取 2* 3 = 6 次。第一个循环中有 2 个条目,内部循环中有 3 行:后缀:_1 _2 inFile:AA AB AC 结果:AA_1 AB_1 AC_1 AA_2 AB_2 AC_2
  • 提示:一个文件需要反复倒带。请注意在倒带之前清除所有标志。

标签: c++ while-loop console std getline


【解决方案1】:

恕我直言,一个更好的方法是将文件读入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 状态。

【讨论】:

  • 谢谢,看起来有点复杂,但确实有效.. :)
  • @midas_96:在现代,从内存读取比从文件读取要快,并且有足够的内存来处理大多数情况。很久以前,内存是宝贵的、小而昂贵的(比磁带驱动器或其他存储设备更昂贵),因此文件被破坏是意料之中的。
  • Thomas 的回答是好的,但如果能指导初学者编写具有良好实践的代码,比如将代码拆分成更小更易读的部分,那就太好了:wandbox.org/permlink/PitbPMJrKP154FRc
猜你喜欢
  • 1970-01-01
  • 2011-11-02
  • 2018-07-24
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多