1

As much as I tried to find a similar version in the question here, I couldn't find something.. so I am asking your help. After reading some numbers from a textfile (now in string format), I split them in rows and columns and add them to a 2d-array (in string format as well). Now I want to convert everythinh in integers so that I can play with sorting the numbers out later. Here is my code...

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using System.IO;

 namespace ArrayProgram
 {
   class Program
 {
    int number = 0;
    int i = 0;
    int k = 0;
    string strnum;


    public void onetohundredints()  
    {
        StreamWriter writer = new StreamWriter("numberstored.txt");

        for (i = 0; i < 10; i++)
        {

            for (k = 0; k < 10; k++)
            {
                number++;

                Console.Write(number + " ");
                strnum = number.ToString();  
                writer.Write(strnum + " ");
            }

            Console.WriteLine();
            writer.WriteLine();
        }
            writer.Close();
    }

    public void readints()
    {
        StreamReader reader = new StreamReader("numberstored.txt");
        string data = reader.ReadToEnd();
        reader.Close();

        string[,] dataarray = new string[10,10];
        int[] numbers = new int[100];

        string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);

        for(int i=0; i<=dataperlines.Count()-1; i++)
        {
            string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (int j=0; j<=numbersperrow.Count()-1; j++)
            {            
                dataarray[i, j] = numbersperrow[j];
            }
        }

    }


    public static void Main(string[] args) 
    {
        Program prog = new Program();
        prog.onetohundredints();
        prog.readints();
        Console.ReadKey();
    }
}
}

After I insert the number into the 2d-array, how do I convert all of it in integers?

1
  • dataarray[i,j] = int.Parse(numbersperrow[j]) will be your friend :) The safe way is to use int.TryParse(numbersperrow[j], out dataarray[i,j]). So if there's anything else than an number in numbersperrow[j] it wont throw an exception, the value of dataarray[i,j] will stay at 0 Commented Jan 14, 2016 at 21:44

3 Answers 3

1

If you don't have a particular reason to have an array of strings, you can just save you data as int in the first place. Just change your inner for loop to do:

var parsed = int.TryParse(numbersperrow[j], out dataarray[i, j]);
if (!parsed)
{
    // Error
}

While that should work, I would suggest to re-write your ReadData method to look similar to the sample below.

public int[,] ReadData(string filePath, int xDimension, int yDimension)
{
    var results = new int[xDimension, yDimension];

    var lines = File.ReadLines(filePath);

    for (var i = 0; i < allLines.Count(); i++)
    {
        var values = lines[i].Split(new[] { ' ' }, 
                                    StringSplitOptions.RemoveEmptyEntries);

        for (var j = 0; j < values.Count(); j++)
        {
            var parsed = int.TryParse(values[j], out results[i, j]);
            if (!parsed) { }
        }
    }

    return results;
}
Sign up to request clarification or add additional context in comments.

Comments

0

You're putting everything into a string array. That array can only hold strings, not numbers. If you want to make the 2d array hold numbers, define it as int[,] dataarray = new int[10,10]; Next, in the final loop, simply do dataarray[i, j] = Convert.ToInt32(numbersperrow[j]);

Edit: You can use int.TryParse(numbersperrow[j], out value) if you aren't sure that numbersperrow[j] will be a number. Value will return false if the conversion is not successful.

Comments

0

I am happy to say that both solutions work. I now have my numbers in my 2d array. But now I wish to play with them. Let's say that I want the numbers printed on the screen in reverse order.

Having this correct solution:

        int numbers;
        int[,] dataarray = new int[10,10];
        string[] dataperlines = data.Split(new[] { '\r','\n' },StringSplitOptions.RemoveEmptyEntries);

        for(int i=0; i<=dataperlines.Count()-1; i++)
        {
            string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (int j=0; j<=numbersperrow.Count()-1; j++)
            {
                numbers = int.Parse(numbersperrow[j]);
                dataarray[i, j] = numbers;
                Console.Write(numbers + " ");
            }
            Console.WriteLine();
        }

I know that I have to make a double for loop. But how do I write a succesful syntax for the numbers to be printed properly? I also tried this:

int[,] reversedarray = new int[10, 10];
reversedarray[i, j] = Array.Reverse(dataarray[i,j]); 

but the dataarray[i,j] becomes red and the error "cannot convert from int to system.Array occurs... what am I missing?

I also tried this...

for (i = 10; i <= dataperlines.Count(); i--)
        {
            string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
            for (j =10; j <= numbersperrow.Count(); j--)
            {
                numbers = int.Parse(numbersperrow[j]);
                reversedarray[i, j] = numbers;

                Console.Write(numbers + " ");
            }
            Console.WriteLine();
        }

But I have an IndexOutOfRange exception coming from

string[] numbersperrow = dataperlines[i].Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

I understood that since I splitted the columns into rows too, it is unecessary to write it again, but I am stuck. I tried simplifying the code since I have my 2darray with its elements and I my tries were fallacious. Any more suggestions?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.