Lame File Operations



  • Hello Guys!

    Recently i have started fooling around (for training purposes) and i came up with a "project", that depending on a person's Gender, it picks a random japanese Family- and Male/Female name from the corresponding ".txt".
    Thing is, i don't quite know how to pick a random line from a txt... i already numbered the lines in my files, and basicly what i'd like to do is search the line in the file that, where the line number matches my random number, then take the number out and show it up in the corresponding label. So far this is what i've got:

    @QString familyname ="";
    int famrand =qrand() % 76 +1;
    QFile famfile("_familynames.txt");
    if (!famfile.open(QIODevice::ReadOnly | QIODevice::Text)){return;}

    QTextStream in(&famfile);
         while (!in.atEnd()) {
             QString line = in.readLine();
             process_line(line);
             if(famrand <10)
             {
                 //this is wehre i'd like to cut off the 1st character from the line
             }//IF
             else
             {
                 //this is wehre i'd like to cut off the first 2 characters from the line
             }//else   
         }//WHILE@
    

    Thing is, for some reasons it deosn't even recognise the "process_line(line);" part, although i have already included <QFile>.

    If you'd have a lil' spare time to think about a solution for a lame rookie, i'd really really apprechiate it :D

    Thanks, and have a nice day: Ryseth


  • Moderators

    There is no function named "process_line()" in QString or QFile, no wonder it fails there :) Remove that line.

    For your randomizer's loop, I would do something like this:
    @
    for (int i = 0; !in.atEnd(); ++i) {
    QString line = in.readLine();
    if (i == famrand) {
    // Do your stuff here
    }
    }
    @

    If you really want to read the line number from file, that make sure you use a convention (for example, the line has to start with number and then the content follows after a space), then you can use this code:
    @
    QString line = in.readLine();
    QStringList lineParts = line.split(" "); // split by space. First element is your number

    int lineNumber = lineParts.at(0).toInt();
    @

    This approach requires some additional checking, though (to allow for errors in the file, or lines that are intentionally not numbered).



  • Wow, Thanks :D

    eventually i copied my files into an array, since than it is working smoothly :)

    Thank you for your reply, and wish you a nic eday: Ryseth


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.