I’m writing a program that will guess words taken from a big text file. One step is taking user input to determine the length of the string.
edit: added full code, made some changes
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int i(0),n(0),counter(0),limit(0);
char words[60000][30];
int initarray() {
int length(0);
string line;
char temp;
ifstream wordlist ("text.txt");
if (wordlist.is_open())
{
while (wordlist.good())
{
getline (wordlist,line);
length=line.length();
for (n=0;n!=length;n++)
{
temp=line.at(n);
words[i][n]=temp;
}
i++;
counter++;
}
}
else
{
cout<<"file not opened";
}
wordlist.close();
return 0;
}
int selectlength()
{
int length;
bool shorter(false),longer(false);
cout <<"length of word"<<endl;
cin >> length
limit=counter;
counter=0;
for (i=0;i<limit;i++){
for (n=0;n!=length;n++){
if (words[i][n]=='\0')
{
shorter=true;
break;
}
}
if (words[i][length+1] != '\0')
{
longer=true;
}
if (longer==true || shorter==true)
{
i--;
}
}
return 0;
}
int printresults(){
for (i=0;i!=counter;i++){
for (n=0;n<=20;n++){
cout << words[i][n];
}
cout <<endl;
}
return 0;
}
int main() {
initarray();
selectlength();
printresults();
return 0;
}
but my problem is happens whenever the program, which compiles fine, gets to the “cin” part to read user input for the length. When I enter in any number and hit enter, nothing happens. The program is still running, and just keeps taking input indefinately. Any help? Could it have anything to do with my using ifstream earlier in the prigram, albeit in a different function?
You’ve got an infinite loop in
selectlength(). The outerforloop doesn’t terminate because you’re decrementingi(the loop counter) inside the loop (not a good idea, perhaps find a better way).I think you’re not terminating on the last line in the input file.
longerandshorterwill both be true andlimitwill never be reached. Put in a test for this in the loop:That will at least stop the infinite loop and allow you to relook at your logic (it’s not clear what
longerandshorterwill be used for.A few general comments:
char words[x][y]you usestd::vector<std::string> words;ifstatement is easier to read like this:if (longer || shorter)than how you have it.void.You’re also setting the global
counterto 0 insideselectlength()but you still need it later inprintresults()so you’ll get no output.