Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text file only reading odd OR even lines?

Tags:

c#

file-io

I'm trying to write a little C# program that reads from a text file and lets you choose a line to print out.

For some reason, it will only print lines 1,3,5,etc.

If I change the bit that says int chooseLine = Convert.ToInt32(input); to int chooseLine = (int)Convert.ToInt64(input);, then it only prints even lines.(0,2,4,6,etc).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Steve
{
    public static int count = 0;
    public static String[] steveTalk;
    public static void Main()
    {
        using (StreamReader r = new StreamReader("Steve.txt"))
        {
            string line;
            while ((line = r.ReadLine()) != null)
            {
                count++;
            }
        }
        using (StreamReader sr = new StreamReader("Steve.txt"))
        {
            int i = 0;
            steveTalk = new String[count];
            String line;
            while ((line = sr.ReadLine()) != null)
            {
                steveTalk[i] = line;
                Console.WriteLine(steveTalk[i]);
                i++;
            }
        }
        while (true)
        {
            string input = Console.ReadLine();
            int chooseLine = Convert.ToInt32(input);
            try
            {
                Console.WriteLine(steveTalk[chooseLine]);
            }
            catch
            {
                Console.WriteLine("Error! Not a number or array index out of bounds");
            }
            Console.ReadLine();
        }
    }
}

Any ideas?

like image 840
Ari Lotter Avatar asked Nov 18 '25 05:11

Ari Lotter


1 Answers

I'd like to suggest the System.IO.File.ReadAllLines(filename) method.

string []lines=System.IO.File.ReadAllLines("Steve.txt");

string input ;

while ((input = Console.ReadLine()) != "end")
    {
        int chooseLine;
        int.TryParse(input,out chooseLine);
        if(chooseLine<lines.Length)
         {
           Console.WriteLine(lines[chooseLine]);
         }
    }
like image 93
KV Prajapati Avatar answered Nov 19 '25 20:11

KV Prajapati