Reputation: 59
I am reading a text file using C#.Net v3.5 express 2010 containing integers in the format
18 11 2 18 3 14 1 0 1 3 22 15 0 6 8 23 18 1 3 4 10 15 24 17 17 16 18 10 17 18 23 17 11 19
by
string[] code = System.IO.File.ReadAllLines(@"C:\randoms\randnum.txt");
i then placethis into a string by
string s1 = Convert.ToString(code);
And need to be able to read this into an int array for some mathematical processing.
I've tried everything suggested on this site under other posts on this topic, including parsing, and covert array but once I attempt this I get the dreaded "input string is not in a correct format" message
Upvotes: 2
Views: 680
Reputation: 37070
Some of these answers are great, but if your file contains any strings that can't be converted to an int, int.Parse()
will throw an exception.
Although slightly more expensive, consider doing a TryParse instead. This gives you some Exception handling:
int tmp = 0; // Used to hold the int if TryParse succeeds
int[] intsFromFile = System.IO.File
.ReadAllText(@"C:\randoms\randnum.txt")
.Split(null)
.Where(i => int.TryParse(i, out tmp))
.Select(i => tmp)
.ToArray();
Upvotes: 2
Reputation: 20764
var intArray = File.ReadAllText(@"C:\randoms\randnum.txt")
.Split((char[]) null, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
Upvotes: 2
Reputation: 74365
It's a one-liner, really. This will give you a 1-dimensional array of integers in the file:
private static rxInteger rxInteger = new Regex(@"-?\d+") ;
...
int[] myIntegers1 = rxInteger
.Matches( File.ReadAllText(@"C:\foo\bar\bazbat") )
.Cast<Match>()
.Select( m => int.Parse(m.Value) )
.ToArray()
;
If you want it to be a 2-dimensional ragged array, it's not much more complicated:
int[][] myIntegers2 = File
.ReadAllLines( @"C:\foo\bar\bazbat" )
.Select( s =>
rxInteger
.Matches(s)
.Cast<Match>()
.Select( m => int.Parse(m.Value) )
.ToArray()
)
.ToArray()
;
[implementation of validation and error handling left as an exercise for the reader]
Upvotes: 0
Reputation: 25370
you can use LINQ:
var ints = code.SelectMany(s => s.Split(' ')).Select(int.Parse).ToList();
This will take your list of space-separated numbers and flatten them into a one-dimensional List of ints
Upvotes: 2
Reputation: 4395
At first glance, it appears the problem is that you're reading in numbers using ReadAllLines
. This will return an array of strings where each string represents one line in your file. In your example it appears that your numbers are all on one line. You could use System.IO.File.ReadAllText
to get a single string. Then use .Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries);
to get the array of strings your looking for.
string allTheText = System.IO.File.ReadAllText(@"C:\randoms\randnum.txt");
string[] numbers = allTheText.Split(new char[]{}, StringSplitOptions.RemoveEmptyEntries);
Upvotes: -1