-2

Trying to create a program and I am currently using a string for track titles but getting the error below, here is the code where the error is appearing

string TotalTracks; 
TotalTracks = loadfile.ReadLine();
int32TotalTracksInt = Convert.ToInt32(TotalTracks); 
user9405863
  • 1,506
  • 1
  • 11
  • 16
dave
  • 9
  • 1
  • 1
  • 4
  • 1
    Possible duplicate of [Input string was not in a correct format](https://stackoverflow.com/questions/8321514/input-string-was-not-in-a-correct-format) – Sudsy1002 Apr 17 '18 at 19:49
  • What was the value for total tracks after the read line? – Greg Apr 17 '18 at 19:50
  • for (int TrackNumber = 0; TrackNumber <= TotalTracksInt; TrackNumber++) – dave Apr 17 '18 at 19:51
  • 1
    So you passed a loop to an integer? – Greg Apr 17 '18 at 19:52
  • What does `TrackNumber` have to do with `TotalTracks`? – NetMage Apr 17 '18 at 19:53
  • yes as i'm reading a file so will be needed to loop until the entire file has been read – dave Apr 17 '18 at 19:53
  • Well, you answered your own question an integer isn't a loop. Sounds like your missing some fundamental knowledge, is this a console application or some file you're reading? – Greg Apr 17 '18 at 19:54
  • a file that im reading – dave Apr 17 '18 at 19:55
  • 1
    variable TotalTracks is not valid value to be converted to Int32. Debug and see what you get in TotalTracks before executing Convert.ToInt32 – Alvin Apr 17 '18 at 19:55
  • The file has track names, or numbers? What exactly are you trying to do? – Greg Apr 17 '18 at 19:58
  • i am creating a jukebox so reading track names but they also have numbers to display what genre it is based on the number – dave Apr 17 '18 at 20:10

4 Answers4

0

The Convert.ToInt32 method will throw an exception if the string is not an integer.

I would suggest making sure the result of loadfile.ReadLine() is a valid integer.

  • i have very basic knowledge so what do you mean by this thanks – dave Apr 17 '18 at 20:03
  • 1
    What Jean means is that it is up to you the programmer to check the data type before using the value. In your code the variable TotalTracks is a string. You're reading one line into that variable (so the variable is still a string). You then try to convert the string to an integer. That's where the error is being thrown. Here's a code hint - create a numeric variable (int, double, etc) and read your file in a loop, add to the numeric for each line you read. – JazzmanJim Apr 17 '18 at 20:20
0

More than likely your error is due to the data input, if the input wasn't sanitized the convert method may be throwing an error since the value cannot be converted to an integer. Some fundamental knowledge appears to be missing, based on your comment.

"I'm reading a file."

public static IEnumerable<string> ReadTrackFile(FileInfo file) 
{
     var line = String.Empty;
     using(StreamReader reader = File.OpenText(file.FullName))
          while((line = reader.ReadLine()) != null)
               yield return line;
}

So we've created a method to read the contents of our file. The method also captured all the individual lines. Due to the lack of clarification I'll assume you have a delimited file with the following format.

Jimmy Hendrix - Greatest Hits - 1 - Gypsy Eyes

So we would shape our object like the following.

public class Music
{
     public string Artist { get; set; }
     public string Album { get; set; }
     public int TrackNumber { get; set; }
     public string TrackName { get; set; }
}

Now that our object is defined, we would do something along these lines.

var output = ReadTrackFile(...);
foreach(var record in output)
   yield return ArtistMapper.MapToObject(record);

Basically the mapping aspect you can do, but you would be mapping those values directly to your object. But that would be a more appropriate approach.

As for your validation, you can simply do the following.

int.TryParse(value, out output);

You could then use output, but it'll hold zero as a default or you can conditionally check to make sure a value is an integer before attempting to use. Code flow and application requirements would specify which approach to use.

Greg
  • 11,302
  • 2
  • 48
  • 79
0

Ok the problem is obvious that you are not getting valid data from this method loadfile.ReadLine();
Hence the error 'Input string was not in a correct format.'
Code

var tracks = loadFile.ReadLine();
if(int.TryParse(tracks, out int totalTracks)
     return totalTracks;

throw new Exception("Invalid data");
Alvin
  • 290
  • 5
  • 25
  • 1
    I modified your code because it could be condensed drastically. – Greg Apr 17 '18 at 20:36
  • i changed the code to the new one but getting the message this int32track does not exist in current context – dave Apr 17 '18 at 20:48
  • You need to declare totalTracks to capture output data. Try now with new code. – Alvin Apr 17 '18 at 20:58
  • @Help You actually don't have to do that in C#, it is called an inline scope decorator. You can now use in the original code. https://www.codeproject.com/Tips/1175809/Csharp-New-Inline-Out-Variables – Greg Apr 17 '18 at 21:12
  • @Greg Hmmm in C# 7 nice to know. Thank you. – Alvin Apr 17 '18 at 21:18
  • @Greg If I understood correctly then your edited answer is missing **int** keyword right after **out** keyword? – Alvin Apr 17 '18 at 21:25
  • @Help Yeah, I missed that part. Sorry, but yes that looks correct. – Greg Apr 17 '18 at 21:32
0

The section

loadfile.ReadLine();

is returning some kind of non-numeric characters. Int32.TryParse will tell you if the string can be converted, you can use this as a condition to convert (if possible) or proceed with error handling. Example:

        var text = "31235";

        //returns true or false if the number can be parsed / converted
        var isValidNumber = Int32.TryParse(text, out int result);
        if (isValidNumber)
        {
            Convert.ToInt32(text);
        }
        else
        {
            //error handling here
        }