Why is my string being converted to ASCII when it's read in?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Alex Dransfield
    New Member
    • Jan 2011
    • 46

    Why is my string being converted to ASCII when it's read in?

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Collections;
    
    namespace LinearSearch
    {
        class Program
        {
            static void Main(string[] args)
           {
                string toFind = "";
                Console.WriteLine("Linear Search");
                Console.Write("Enter the item to find: ");
                toFind = Convert.ToString(Console.Read());
                Console.WriteLine(toFind);
                StreamReader sr = new StreamReader("Cars.txt");
                ArrayList al = new ArrayList();
                String lines = String.Empty;
                while ((lines = sr.ReadLine()) != null)
                {
                    lines = sr.ReadLine();
                    al.Add(lines);
                }
                foreach (string line in al)
                {
                    if(line == toFind)
                    {
                        Console.WriteLine("The item of {0} was found", line);
                        break;
                    }
                }
                sr.Close();
                Console.WriteLine("Unable to find the item");
                Console.ReadLine();
            }
        }
    }
    I'm not sure why this is happening, but whenever I enter a string into the console it is being converted to the ASCII equivalent. For example, if I read in 'A' it is converted to 65, and because of this the item in the list is not found. What's going on here?
  • Aimee Bailey
    Recognized Expert New Member
    • Apr 2010
    • 197

    #2
    Couple of things that may help...

    1. An easier way of reading a file, and representing each line in an array is this:

    Code:
    string[] al = File.ReadAllLines("cars.txt");
    2. Console.Read() actually returns the integer value of the next character read. Instead use Console.ReadLin e()


    bobs your uncle, things should go a bit smoother :)


    Aimee.

    Comment

    Working...