Jump to content

String to int conversion C#

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
veda87

veda87

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
Hi,
I have a file that contains
360    52   155      ! Global variables
123    23     55    34    234    ! other variables
I wanted to read this file and take out the integer value. I have coded to read the file, take the line, and convert the string into integer.
My code is here
FileStream filefs = new FileStream("file.txt", FileMode.Open);
StreamReader filesr = new StreamReader(xyzfilefs);
string Data = filesr.ReadLine();
string[] temp = Data.Split(' ');
for (int jjj = 0, iii = 0; jjj < temp.length; jjj++)
{
    if (temp[jjj] != "")
    {
    x[iii] = (int)Double.Parse(temp[jjj],
                  System.Globalization.NumberStyles.Integer);
    iii++;
    }
}
When I execute the program, it gives me

Quote

Format Exception was unhandled
I think it is converting a non int into integer... Can anyone tell me, how to solve this problem.

#2
veda87

veda87

    Programmer

  • Members
  • PipPipPipPip
  • 126 posts
I solved it...
I wrote a function to check whether it is int or not....
The modified code...
FileStream filefs = new FileStream("file.txt", FileMode.Open);
StreamReader filesr = new StreamReader(xyzfilefs);
string Data = filesr.ReadLine();
string[] temp = Data.Split(' ');
for (int jjj = 0, iii = 0; jjj < temp.length; jjj++)
{
    if (temp[jjj] != "" && IsNumeric(temp[jjj]))
    {
    x[iii] = (int)Double.Parse(temp[jjj],
                  System.Globalization.NumberStyles.Integer);
    iii++;
    }
}

static bool IsNumeric(string input)
        {
            try
            {
                int.Parse(input);
                return true;
            }
            catch
            {
                return false;
            }
        }
Thanks....