Home > Software design >  C#: How to make Stream Reader to Int
C#: How to make Stream Reader to Int

Time:03-31

I'm reading from a file with numbers and then when I try to convert it to an Int I get this error, System.FormatException: 'Input string was not in a correct format.' Reading the file works and I've tested all of that, it just seems to get stuck on this no matter what I try. This is what I've done so far:

StreamReader share_1 = new StreamReader("Share_1_256.txt");

string data_1 = share_1.ReadToEnd();

int intData1 = Int16.Parse(data_1);

Image showing the error I get.

If Parse is commented out it prints the data And then if parse is in it doesn't print anything.

CodePudding user response:

As we can see in your post, your input file contains not one number but several. So what you will need is to iterate through all lines of your file, then try the parsing for each lines of your string.

EDIT: The old code was using a external library. For raw C#, try:

using (StringReader reader = new StringReader(input))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // Do something with the line
    }
}

In addition, I encourage you to always parse string to number using the TryParse method, not the Parse one.

You can find some details and different implementations for that common problem in C#: C#: Looping through lines of multiline string

CodePudding user response:

parser every single line

while (!reader.EndOfStream) 
{ 
    string line = reader.ReadLine(); 
    int intData1 = Int16.Parse(line);
} 

CodePudding user response:

You can simplify the code and get rid of StreamReader with a help of File class and Linq:

// Turn text file into IEnumerable<int>:
var data = File
  .ReadLines("Share_1_256.txt")
  .Select(line => int.Parse(line));

//TODO: add .OrderBy(item => item); if you want to sort items

// Loop over all numbers within file: 15, 1, 48, ..., 32
foreach (int item in data) {
  //TODO: Put relevant code here, e.g. Console.WriteLine(item);
}
  • Related