willkara
willkara

Reputation: 177

Trying to get the largest int in each line of a file and sum the result

When I try and run my code I get the error:

Input string was not in a correct format.

I am trying to find the largest int in each line of a text file and then add them all up.

I am sure that there are no letters in this file and everything is separated by a space.

Here is my code:

int counter = 0;
string line;

List<int> col = new List<int>();

// Read the file and display it line by line.
System.IO.StreamReader file =
    new System.IO.StreamReader(label3.Text);
while ((line = file.ReadLine()) != null)
{
    int[] storage = new int[10000];

    Console.WriteLine(line);
    counter++;
    string s = line;

    string[] words = s.Split(' ');

        for (int i = 0; i < words.Length; i++)
        {
            storage[i] = Convert.ToInt32(words[i]);

        }

        int large = storage.Max();

        col.Add(large);
        Console.WriteLine(" ");

        foreach (int iii in col)
        { 
            Console.WriteLine(iii); 
        }

        int total = col.Sum();
        Console.WriteLine(total);

}

file.Close();

// Suspend the screen.
Console.ReadLine();

Upvotes: 1

Views: 141

Answers (4)

digdig
digdig

Reputation: 240

You're either converting out of size, or attempting to parse a return carriage '/r'

Make sure you're trimming your input.

My solution:

    static void Main(string[] args)
    {
        int linecount = 100;

        string path = @"C:\test\test.txt";
        Random rand = new Random();

        //Create File
        StreamWriter writer = new StreamWriter(path, false);
        for (int i = 0; i < linecount; i++)
        {
            for (int j = 0; j < rand.Next(10, 15); j++)
            {
                writer.Write(rand.Next() + " ");
            }
            writer.WriteLine("");
        }

        writer.Close();


        //Sum File
        long sum = Enumerable.Sum<string>(
            (new StreamReader(path)).ReadToEnd().Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries),
            l => Enumerable.Max(
                l.Split(' '),
                i => String.IsNullOrEmpty(i.Trim()) ? 0 : long.Parse(i.Trim())
                )
            );
    }

Upvotes: 0

I believe that the line in your code that can cause this error is

Convert.ToInt32(words[i]);

Now, when you're running this application in debug mode(which you probably are) in visual studio, you have a way to check what's going on in your program when the exception happens.

At the very very bottom of your screen is going to be some tabs. these tabs include your error list among other things. The ones I like to use are called "Locals" and "Watch". You can use the Locals tab.

When you click on the Locals tab, you should see a tree structure of all the local variables in your program. if you expand the words variable, you should see all the individual members of the array. you should also be able to see the variable i check the i'th member of your words array, and make sure that it's an integer, and not something else.

Upvotes: 0

Orkun
Orkun

Reputation: 7248

I did a quick test and it is likely you get the error in the line

 storage[i] = Convert.ToInt32(words[i]);

If so, make sure what you are trying to convert is an integer and not an empty string, for example.

Upvotes: 0

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

It's possible that target string cannot be stored in a 32 bit integer. You can try parsing to ulong type. Take a look at Integral Types Table and Floating-Point Types Table.

Instead of doing Convert.ToInt32(), try int.TryParse(). It will return a bool value telling you if operation succeeded, and it has an out parameter where it will place result of parse operation. TryParse operation is also available on other numeric types if you decide you need them.

E.g.

int val;
string strVal = "1000";
if (int.TryParse(strVal, out val))
{
  // do something with val
}
else
{
  // report error or skip
}

Upvotes: 2

Related Questions