Adblock breaks this site

read a random line from text file

Discussion in 'Programming General' started by hampe-92, Nov 10, 2008.

  1. hampe-92

    hampe-92 Forum Addict

    Joined:
    Jul 10, 2008
    Posts:
    328
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    Hi!
    I have been trying to figure out how I read a single, random line from a text file...

    so, when i click "button1" I want to get a random line from the file "c:\users\profile\test.txt" I have been googleing all day but havent found/understod... so please help me :/

    by the way... the text file looks something like this, but the number of lines should be editable so if I write more lines the random will count with those too:
    Code:
    Line a
    Line b
    Line c
    Tyvm in advance!
    I have already got headache from this... :confused:
     
  2. Swan

    Swan When They Cry...
    Retired Global Moderator

    Joined:
    Jan 23, 2007
    Posts:
    4,957
    Referrals:
    0
    Sythe Gold:
    0
    Sythe's 10th Anniversary Member of the Month Winner
    read a random line from text file

    I'll help you when I get home from school if someone else doesn't. Be around 6-7 hours.
     
  3. slashshot007

    slashshot007 Active Member

    Joined:
    May 6, 2006
    Posts:
    164
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    hmm well its pretty simple,
    [edit]DAMN IT, i though this was java. Oh well you probably wont need this, but its not worth deleteing, i put hard work into it.[/edit]
    Use these imports:
    Code:
    import java.util.*;
    import java.lang.Math;
    First, put all your code, inside this try, catch statement:
    Code:
    try{
       //code goes here
    }catch (FileNotFoundException e) {
       System.out.println(e);
    }
    Make a scanner:
    Code:
    Scanner reader = new Scanner(new File("filename.txt"));
    Now, we will use the scanner, to save all of this into an ArrayList (very usefull)
    again, not too sure if this will work 100% but you should get the jist.
    Code:
    ArrayList<String> ar = new ArrayList<String>();
    while (reader.hasNext()) {
       ar.add(reader.nextLine());
    }
    ok, once you have the total, create a random number.
    Code:
    int randomnum = Math.random()*ar.size();
    Then, you have everything you need, just print out the random number, which should be in the arraylist.

    Code:
    System.out.println(ar.get(randomnum));
    
    I didn't even open up notepad or compile this or anything, so some of the cases may be off, but that is the basic jist of it.
     
  4. Swan

    Swan When They Cry...
    Retired Global Moderator

    Joined:
    Jan 23, 2007
    Posts:
    4,957
    Referrals:
    0
    Sythe Gold:
    0
    Sythe's 10th Anniversary Member of the Month Winner
    read a random line from text file

    Okay, as promised, I will help you now.

    Create a console application, you have no need of Windows Forms for something so simple. Note that because a console application's main() method is static (Actually, all application's main method is static, if you look in Program.cs) you will need to declare any globally scoped variables in that file as static if they are referred to by main.

    For this, the easiest way will be to use an array of strings, and the easiest way to make an array is with the ArrayList class, as you can just use "ArrayList.Add()" rather than going through all of this shit just to resize one little array.

    Add these includes:
    Code:
    using System.IO;
    using System.Collections;
    System.IO contains the StreamReader class which is useful for reading the contents of files. System.Collections contains the ArrayList class which I explained earlier.

    Inside your class, create a StreamReader variable in main() like so:
    Code:
    StreamReader fileReader = new StreamReader(@"C:\test\test.txt");
    In this instance, I will be using C:\test\test.txt as the file I am reading. Alter the path as you wish. If you want to create a globally scoped StreamReader instance, by all means use this code:
    Code:
    static StreamReader fileReader;
    And initialize it in main() like so:
    Code:
    fileReader = new StreamReader(@"path:\to\file");
    The StreamReader class provides many ways to read a file. If you don't know how Streams work, I will tell you the basics of using a Stream reader. Notice there is a class member called "StreamReader.EndOfStream". This is a boolean which tells you whether or not you have reached the end of the stream, and yields true once you have reached the end. This is ideal for looping through the file if you're going to access the file more than once. An ideal way of doing this would be with a while or do-while loop. For example:
    Code:
    while(!fileReader.EndOfStream)
    {
        // Insert file reading code, such as fileReader.ReadLine()
    }
    There is of course, a StreamReader.ReadToEnd() method available, but for the purpose of adding each individual line to an array, reading each line separately of course makes more sense.

    Now, before you go and read from the file, you will want an array to store the data in! Simply, you can use the ArrayList class, part of the System.Collections namespace, which is ideal for this purpose as mentioned earlier, because you can just use the ArrayList.Add(data) method to add each line. Declare an ArrayList like so:
    Code:
    ArrayList fileData = new ArrayList();
    Now, to add each line to ArrayList, all you need to do is loop through the stream and do the following:
    Code:
    fileData.Add(fileReader.ReadLine());
    Hint: Remember the EndOfStream variable I discussed earlier?

    The other excellent thing about ArrayLists, is that you can access each element like a normal array. For example, I can simply access the first element of an ArrayList by using ArrayList[0]. To access a random line, you will need to generate a random number and access an element of the ArrayList using that number.

    Random numbers can be a little confusing. You actually need to seed the random number generator before you generate, otherwise you will get the same output every time you start your program. To do this, a common method is to get some form of current time. In this example, I'll use the DateTime class, and use the amount of milliseconds that have elapsed for today as my seed. In languages like C++, you used to have to seed a random function by using srand(), but with C#'s Random() class, you can do this in the initializer, like so:
    Code:
    Random randomLineGenerator = new Random(DateTime.Now.Millisecond);
    And to generate a random number to access your array with, the following:
    Code:
    int randomIndex = randomLineGenerator.Next(fileData.Count);
    Now, remember how I said you can access an ArrayList as a normal array? All you have to do is print the line and you're done!

    Code:
    Console.WriteLine("Line {0}: {1}", randomIndex, fileData[randomIndex]);
    Console.Write("\nPress any key to continue ...");
    Console.ReadKey();
    And that my friend, is how you access a random line of a file. There are probably more efficient ways of doing such, but this is definitely a simple one.
     
  5. hampe-92

    hampe-92 Forum Addict

    Joined:
    Jul 10, 2008
    Posts:
    328
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    First of I want to thank you for taking time and writeing all this to help me :)
    But I am making a wfapp where I will use the random picked line later... I maybe should have told you that before.. sorry for that, acctually I am makeing a hangman game just to learn to read/write to files and so on... but I guess this will work pretty much the same for a wfapp as it does for a console app...
    I had already been playing around with StreamReader and so, but when i used streamReader.ReadLine() it just read the first line in my text file...

    but I will take a close look at this soon, proabobly tomorrow don't have very much time atm, and play around with it...

    by the way, just a quick little question... you don't happend to know how to write a relative path in C#?
    i mean, you can't write @"%userprofile%\appdata\local\temp".. :confused:

    anyway, Tyvm for your help! your my idol Swan ;)
     
  6. Swan

    Swan When They Cry...
    Retired Global Moderator

    Joined:
    Jan 23, 2007
    Posts:
    4,957
    Referrals:
    0
    Sythe Gold:
    0
    Sythe's 10th Anniversary Member of the Month Winner
    read a random line from text file

    You can use the following to get specific paths relative to the user:
    Code:
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
    This returns a string containing the path to my desktop, which is "C:\Users\Dave\Desktop". Change Environment.SpecialFolder.Desktop to anything that suits your purpose, i.e. Environment.SpecialFolder.ApplicationData.
     
  7. slashshot007

    slashshot007 Active Member

    Joined:
    May 6, 2006
    Posts:
    164
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    swan, you probably looked at what i did, and converted it all to c#, it really looks almost exactly the same. i'm onto you old bugger.
     
  8. hampe-92

    hampe-92 Forum Addict

    Joined:
    Jul 10, 2008
    Posts:
    328
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    ok tyvm :)
     
  9. Swan

    Swan When They Cry...
    Retired Global Moderator

    Joined:
    Jan 23, 2007
    Posts:
    4,957
    Referrals:
    0
    Sythe Gold:
    0
    Sythe's 10th Anniversary Member of the Month Winner
    read a random line from text file

    Are you saying you have legal rights to the classes that Microsoft made for their framework? There is only so many ways you can implement the same thing. >_>
     
  10. hampe-92

    hampe-92 Forum Addict

    Joined:
    Jul 10, 2008
    Posts:
    328
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    lol, atleast he provided me with the right language...
    anyway..
    how would this part been writen to lets say a messagebox?
    Console.WriteLine("Line {0}: {1}", randomIndex, fileData[randomIndex]);
    can u explain that {0} and {1}?
    tyvm in advance :)
     
  11. Swan

    Swan When They Cry...
    Retired Global Moderator

    Joined:
    Jan 23, 2007
    Posts:
    4,957
    Referrals:
    0
    Sythe Gold:
    0
    Sythe's 10th Anniversary Member of the Month Winner
    read a random line from text file

    {0} and {1} are simply shorthands for outputting variables without actually having to close the string. It only works in Console.Write (or variants), or methods that have been made to accept the same sort of arguments.

    For example,
    Code:
    int myint = 52;
    string mystring = "myint's value is";
    Console.WriteLine("{0}: {1}", mystring, myint);
    This could just as easily be written as
    Code:
    int myint = 52;
    string mystring = "myint's value is";
    Console.WriteLine(mystring + ": " + myint)
    I find the former easier to read, some think otherwise. It is really a matter of preference. I'm used to using the printf() function from C/C++, and that uses a similar method of outputting text, so it really is just a preference.

    This is only for the Console. For MessageBoxes and stuff like that, you will need to build the string on your own.

    However, if you really do fancy the whole "{0} {1}" sort of idea, you can use the StringBuilder class, which is part of the System.Text namespace.

    Here's a link: http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx
    Or to be more precise about the "{0} {1}" scenario, the StringBuilder.AppendFormat() method: http://msdn.microsoft.com/en-us/library/hdekwk0b.aspx

    Edit: Just so you know, this works the same sort of way an array would. You access the first "element" with a zero, and go up from there. You can contain however many variables you want in the same statement. For all the compiler cares, you can go to over {9000}.

    Good day ;)
     
  12. hampe-92

    hampe-92 Forum Addict

    Joined:
    Jul 10, 2008
    Posts:
    328
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    hmm.. haveing some trouble here... Its just reading the second line...
    snge huh? ok if it read the first or something but the second?
    oh well... please tell me what i'm doing wrong:confused:
    here is my code:
    Code:
    [SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]Random[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] randomLineGrabber = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]Random[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]([/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]DateTime[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2].Now.Millisecond);[/SIZE]
     
    [SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]private[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]void[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] button1_Click([/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]object[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] sender, [/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]EventArgs[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] e)[/SIZE]
    [SIZE=2]{[/SIZE]
    [SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]StreamReader[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] fileReader = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]StreamReader[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2](path);[/SIZE]
    [SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]ArrayList[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] fileData = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]ArrayList[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]();[/SIZE]
    [SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] randomIndex = randomLineGrabber.Next(fileData.Count);[/SIZE]
    [SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]while[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] (!fileReader.EndOfStream)[/SIZE]
    [SIZE=2]{[/SIZE]
    [SIZE=2]fileReader.ReadLine();[/SIZE]
    [SIZE=2]fileData.Add(fileReader.ReadLine());[/SIZE]
    [SIZE=2]}[/SIZE]
    [SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]string[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] test = (fileData[randomIndex]).ToString();[/SIZE]
    [SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]MessageBox[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2].Show(test);[/SIZE]
    [SIZE=2]fileReader.Close();[/SIZE]
    [SIZE=2]}[/SIZE]
    
    Thx in advance
     
  13. hampe-92

    hampe-92 Forum Addict

    Joined:
    Jul 10, 2008
    Posts:
    328
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    yaay!! :D I got it working!
    after some experimenting by starting from scratch i managed to figure a solution out :D
    here is my code:
    Code:
    [SIZE=2][/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]Random[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] random = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]Random[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]();[/SIZE]
    [SIZE=2] 
    [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]private[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]void[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] button1_Click([/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]object[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] sender, [/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]EventArgs[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] e)
    {
    [/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]StreamReader[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] read = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]StreamReader[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]([/SIZE][SIZE=2][COLOR=#a31515][SIZE=2][COLOR=#a31515]@"C:\Users\Hampus\test.txt"[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]);
    [/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]ArrayList[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] lines = [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]new[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]ArrayList[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2]();
    [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]string[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] line;
    [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]string[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] word;[/SIZE]
    [SIZE=2] 
    [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]while[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] ((line = read.ReadLine()) != [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]null[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2])
    lines.Add(line);
    read.Close();
     
    [/SIZE][SIZE=2][COLOR=#0000ff][SIZE=2][COLOR=#0000ff]int[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2] randomLine = random.Next(0, lines.Count);[/SIZE]
    [SIZE=2] 
    
    word = lines[randomLine].ToString();
     
    [/SIZE][SIZE=2][COLOR=#2b91af][SIZE=2][COLOR=#2b91af]MessageBox[/COLOR][/SIZE][/COLOR][/SIZE][SIZE=2].Show(word);
    }
    [/SIZE]
    You can lock this now if u want to ;) and tyvm for the "lessons" Swan :)
     
  14. Swan

    Swan When They Cry...
    Retired Global Moderator

    Joined:
    Jan 23, 2007
    Posts:
    4,957
    Referrals:
    0
    Sythe Gold:
    0
    Sythe's 10th Anniversary Member of the Month Winner
    read a random line from text file

    What you did there was quite obvious:
    Code:
    fileReader.ReadLine();
    fileData.Add(fileReader.ReadLine());
    
    You were reading two lines.

    Anyhow, here's the code I used when writing up my replies, just for reference:
    Code:
    using System;
    using System.Collections;
    using System.IO;
    
    namespace readRandLine
    {
        class Program
        {
            
    
            static void Main(string[] args)
            {
                StreamReader fileReader = new StreamReader(@"C:\test\test.txt");
                
                ArrayList file = new ArrayList();
    
                while(!fileReader.EndOfStream)
                {
                    file.Add(fileReader.ReadLine());
                }
                
                Random myrand = new Random(DateTime.Now.Millisecond);
                int randomindex = myrand.Next(file.Count);
                Console.WriteLine(file[randomindex]);
    
                Console.WriteLine("\nPress any key to continue...");
                Console.ReadKey();
            }
        }
    }
    This topic can be open for discussion, i.e. Improving upon each other's methods. If it isn't popular, it will slowly make its way to the archives as new topics are created ;).
     
  15. hampe-92

    hampe-92 Forum Addict

    Joined:
    Jul 10, 2008
    Posts:
    328
    Referrals:
    0
    Sythe Gold:
    0
    read a random line from text file

    ahh, I see, I never thought about that I wrote
    fileReader.ReadFile()
    fileData.add(fileReader.ReadFile())
    and you're right, it was indeed quite obvious...
    I guess it would have worked if I removed the first one...
    thx for all tips:)
     
< visual c++ tools for ubuntu | error with control over rs hnadle >


 
 
Adblock breaks this site