0
using System;
using System.IO;

namespace _2._1
{
class Program
{
    public struct nariai
    {
        public string vardas;
        public string pavarde;
        public double pinigai;
    };
    static void Main(string[] args)
    {
        StreamReader failas = new StreamReader("nariai.txt");
        string a = failas.ReadLine();
        int nariuKiekis = int.Parse(a);
        nariai[] narys = new nariai[nariuKiekis];
        string[] info = new string[nariuKiekis];
        for (int i = 0; i < nariuKiekis; i++)
        {
            info[i] = failas.ReadLine();
            string[] informacija = info[i].Split(' ');
            narys[i].vardas = informacija[i];
            narys[i].pavarde = informacija[i + 1];
            narys[i].pinigai = double.Parse(informacija[i + 2]);
            Console.WriteLine("{0} {1} {2}", narys[0].vardas, narys[0].pavarde, narys[0].pinigai);
        }
    }
}
}

My file looks like that. file

And i am getting this error in the console. console

Why it isn't showing the "Almeda Norkute 25.70" ?

Community
  • 1
  • 1
  • Could you add the content of file and error description to the question, so that it remains when question is solved and links you added will became broken? – Belurd Sep 13 '18 at 14:04
  • 1
    Why are you using `i` with `informacija`? – juharr Sep 13 '18 at 14:08
  • If you come across this message, step through your code over the line , where it says the error occurs and check the values of your indices. Then think about why they have the values they have. – Fildor Sep 13 '18 at 14:09

2 Answers2

8

Instead of

narys[i].vardas = informacija[i];
narys[i].pavarde = informacija[i + 1];
narys[i].pinigai = double.Parse(informacija[i + 2]);

write

narys[i].vardas = informacija[0];
narys[i].pavarde = informacija[1];
narys[i].pinigai = double.Parse(informacija[2]);

Your informacija contains one line and one line always has 3 items in your example. If you need i to access these you get the error because you're trying to access position which are not existing.

And use

Console.WriteLine("{0} {1} {2}", narys[i].vardas, narys[i].pavarde, narys[i].pinigai);

Otherwise you would write always the first record in the console ;)

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
0

Instead of informacija[i], informacija[i+1] and informacija[i+2], use informacija[0],informacija[1] and informacija[2] respectively.

And also use index i in console.writeline statement.

for (int i = 0; i < nariuKiekis; i++)
            {
                info[i] = failas.ReadLine();
                string[] informacija = info[i].Split(' ');
                narys[i].vardas = informacija[0];
                narys[i].pavarde = informacija[1];
                narys[i].pinigai = double.Parse(informacija[2]);
                Console.WriteLine("{0} {1} {2}", narys[i].vardas, narys[i].pavarde, narys[i].pinigai);
            }
Mehul Vaghela
  • 478
  • 4
  • 20