user2740970
user2740970

Reputation: 137

Shortest way to verify integer values

i am reading values from the file and checking the values my code is

while (sr.EndOfStream != null)
{
     a= sr.EndOfStream ? "" : sr.ReadLine();
     if (Convert.ToInt32(a) < 1)
     {
         Console.WriteLine(a+ " is not a right value");
         flag = true;
         break;
     }
     b= sr.EndOfStream ? "" : sr.ReadLine();
     if (Convert.ToInt32(b) < 1)
     {
         Console.WriteLine(b+ " is not a right value");
         flag = true;
         break;
     }
     ....

Is there any other way to make my code look good

Upvotes: 1

Views: 184

Answers (3)

Thilina H
Thilina H

Reputation: 5810

The C# language provides some utility methods for this purpose. We describe an easy way to convert strings to ints. This approach avoids exceptions when a string cannot be converted.

        int value;

        if (Int32.TryParse("String Value", out value))
        {
            //Converted
        }
        else
        {
            //Can not parse to Int 
        }

Upvotes: 2

Sayse
Sayse

Reputation: 43330

Writing from my phone so excuse the formatting...

var lines = file.readalllines(path);
var indexes //list
for(int I = 0; I < lines.count; I++)
{
    int current;
    if(!int.TryParse(lines[I], out current)
        indexes.add(I);
}

Indexes will now be a list of every line that is erroneous (0 indexed)

Upvotes: 1

davisoa
davisoa

Reputation: 5439

I would use the very nice TryParse method to validate your input, and process one line each time through the while loop.

while (!sr.EndOfStream)
{
    int a;
    string s = sr.EndOfStream ? "" : sr.ReadLine();
    if (int.TryParse(s, out a))
    {
        // Use the value of a, since it is an integer
    }
    else
    {
        Console.WriteLine(a + " is not a right value");
        flag = true;
        break;
    }
}

Upvotes: 2

Related Questions