PDA

View Full Version : Getting a random string from a QStringList



nickb
19th October 2010, 23:59
I am trying to read in a group of words from a file, then select a random word. This is what I have, it makes sense to me logically, but obviously its wrong, because you cannot pull a QString from a QStringList. Yes, this is a homework assignment, but it is part of a very large project, a dictionary to be exact.

QFile inputFile("C:\\Users\\hisownfoot\\Documents\\Dictionary_3\\wo rdList_new.txt");

// Create an inputstream to handle the file
QTextStream in(&inputFile);

// Insert the text from the file into the QString dictionaryString
QString dictionaryString = in.readAll();
inputFile.close();

// Fills the QStringList with each word in the dictionary string, which are all
// seperated by 2 spaces.
wordList = dictionaryString.split(" ");



int n = wordList.size();
int random_selector;

random_selector = (rand()%n)+1;

QString gameword;
gameword = wordList.at(random_selector);

ui->textBox->append(gameword);

I receive a runtime error upon running this specific area of the program, and it causes it to crash.

Invalid parameter passed to C runtime function.

That is what appears in the application output, and using debugging i determined the line it goes bad at is,

gameword = wordList.at(random_selector);

ChrisW67
20th October 2010, 01:35
What is the value of random_selector when the program fails? Why do you add one to your random selector value?

nickb
20th October 2010, 15:45
the value of random selector is 1 every time the program fails, but regardless it should output the wordlist.at(1) right?

And your right, the +1 makes no sense.

Hostel
20th October 2010, 17:29
Whai is value of wordList.size() ?

Try replace method at( int ) by value( int ). Method value( int ) should work even if int will be out of bounds.http://doc.trolltech.com/4.7/qlist.html#value
Maybe a problem is in different place.

nickb
20th October 2010, 18:41
It appears that wordList.size() is = to 1. I just dont know what to do, it does not have to be done my way specifically, I just need to grab one random word from a text file.

Hostel
20th October 2010, 19:34
If size is 1 then you have only one "word" in wordList. (rand()%1)+1 = 1 but you had a text only under 0 index.



wordList = dictionaryString.split(" ");


In this line is something wrong. Could you give a wordList_new.txt? Maybe separator which you insert into split is bad.

nickb
20th October 2010, 20:27
accordion acorn acrobat actor actress adult advertisement aim air airplane airport terminal, thats the start of it, but there are around 1200 words in it. That exact command works elsewhere in my program.

wysota
20th October 2010, 21:29
Opening the file before trying to read it might be helpful.

nickb
20th October 2010, 21:46
Fantastic, thank you for your sarcasm laced but efficient and perfect reply.