Home > other >  c nested while loop runs only once
c nested while loop runs only once

Time:11-03

Please can you advise, why the inner loop runs only once? I'd like to add suffix to each line of input file and then store the result in output file.

thanks

For example: Input file contains:

AA
AB
AC

Suffix file contains:

_1
_2

Output file should contain:

AA_1
AB_1
AC_1
AA_2
AB_2
AC_2

My result is :

AA_1
AB_1
AC_1

Code:

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

}

CodePudding user response:

IMHO, a better method is to read the files into vectors, then iterate through the 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";
    }
}

Edit 1: no vectors
If you haven't learned about vectors or like to thrash your storage device you could try this:

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).
}

Remember, after the inner while loop, the suffixes file is at the end; no more reads can occur. Thus the file needs to be positioned at the start before reading. Also, the EOF state needs to be cleared before reading.

  • Related