Reputation: 1
I am trying to create a program that is able to read a text file with a random words inside it and be able to count the duplicates and list them into an output text file.
But I am getting problem from the while loop at line 40 that is only looping once. The first word in the input.txt file is "look", and the program is able to find all the duplicates and count them so that it outputs "look 21" into the output file.
When I run the code, only "look 21" is inside the file and nothing else. So I added in a line after the while loops to print out the "word" variable and the "amount variable", and it printed out "look 21" which tells me that it only looped once.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
std::__1::fstream database, input, output, temp;
int formatText()
{
std::string myText;
database.open("database.txt", std::__1::ios::in);
getline(database, myText);
database.close();
for(int i=0; i < myText.size(); i++)
{
if(myText[i] == ' ')
{
myText[i] = '\n';
}
}
input.open("input.txt", std::__1::ios::out);
input << myText;
input.close();
return 0;
}
int main()
{
std::string word, word1;
int amount = 0;
formatText();
input.open("input.txt", std::__1::ios::in);
output.open("output.txt", std::__1::ios::out);
while(getline(input, word))
{
while(getline(input, word1))
{
if(word1 == word)
{
amount++;
}
else
{
output << word1 << '\n';
}
}
output << word << ' ' << amount << '\n';
}
input.close();
output.close();
std::cout << word << ' ' << amount << '\n';
std::cout << "\ndone...\n";
return 0;
}
Upvotes: 0
Views: 220
Reputation: 11321
Your nested while loops are reading from the same file. When inner loop exits, there is nothing left to read for the outer loop.
Also, you don’t want to read the same file multiple times.
Upvotes: 3