How to read in text from a text file and convert the return string to a int value.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • martinsmith160
    New Member
    • Dec 2009
    • 16

    How to read in text from a text file and convert the return string to a int value.

    Does anyone know how to read in data from a text file and initialize a variable to the string value that was read in from the file. E.g

    text file data:
    100
    200
    300

    I want to read in each value and assign it to a variable in my code.
    This is the code I have done so far just to ilistrate my problem.

    Code:
                int x;
                int y;
    
                open_dlg.Filter = "Text documents (.txt)|*.txt";
                if (open_dlg.ShowDialog() == true)
                {
                    string fileName = open_dlg.FileName;
    
                    FileInfo theSourceFile = new FileInfo(fileName);
    
                    StreamReader stream = theSourceFile.OpenText();
    
                    name = stream.ReadLine();
                    x = stream.Read();
                }
    The name assingment works fine because ReadLine() returns a string but the read is returning the wrong value.
  • tlhintoq
    Recognized Expert Specialist
    • Mar 2008
    • 3532

    #2
    X is an int
    But when you read from a stream you get a string, even if the string happens to contain a number. You need to convert the string to a number before you assign it to x

    Code:
    string NewValue = stream.readline();
    int x = convert.ToInt(NewValue;

    Comment

    • martinsmith160
      New Member
      • Dec 2009
      • 16

      #3
      Thanks alot that worked great.

      Comment

      • GaryTexmo
        Recognized Expert Top Contributor
        • Jul 2009
        • 1501

        #4
        There's an alternate method to convert a string to an integer, which is built right into the type.

        Code:
        int x = int.Parse(NewValue);
        That part is basically exactly the same, but the reason I bring it up is because your program will actually throw an exception if the string is not able to be converted to an integer (ie, the string is "45a"). To get around this, you can use the TryParse method from the type.

        Code:
        int x = 0;
        if (!int.TryParse(NewValue, out x)
        {
          // parse failed, do whatever you need to do
        }
        These Parse and TryParse methods exist on all the base types I believe.

        Comment

        Working...