0

How can I re-write this input/output files so that my input file is a comma delimited file (input.csv)?

Input file (input.csv):

Smith,John,87
Doe,Jane,93
Sacramanto,Bob,57

I'm a beginner and my teacher says we must use the line.indexOf() function.

// constant variables
const string INPUT_FILE = "input.txt";
const string OUTPUT_FILE = "output.txt";

// open the input file
StreamReader sr = new StreamReader(INPUT_FILE);

// fields used for input file
string? line = "";

string firstName = "", lastName = "";
double mark = 0;

// variables for calculating average
double total = 0, count = 0, avg = 0;

// read the first line of text from the input file
line = sr.ReadLine();


// continue to read until you reach end of file


while (line != null)
{

string [] values = line.Split(',');

// get firstName
firstName = line;

// read next line & get last name
line = sr.ReadLine();
lastName = line;

// read next line & get mark
line = sr.ReadLine();
mark = Convert.ToDouble(line);

Console.WriteLine(firstName + ' ' + lastName + ": " + mark);

// accumulate 'total' & increment 'count'
total = total + mark;
count++;

// read the next line
line = sr.ReadLine();

}
//close input file
sr.Close();


avg = total / count;
Console.WriteLine("\nClass Average: " + avg);

// open an output file
StreamWriter sw = new StreamWriter(OUTPUT_FILE);

sw.WriteLine(avg);

sw.Close();
halfer
  • 19,824
  • 17
  • 99
  • 186
  • Questions that ask "please help me" tend to be looking for highly localized guidance, or in some cases, ongoing or private assistance, which is not suited to our Q&A format. It is also rather vague, and is better replaced with a more specific question. Please read [Why is "Can someone help me?" not an actual question?](//meta.stackoverflow.com/q/284236). – gunr2171 Apr 30 '22 at 19:50
  • You should use the framework class that exists to parse CSV files: `Microsoft.VisualBasic.FileIO.TextFieldParser`. See [Reading CSV files using C#](https://stackoverflow.com/a/3508572/3744182). Actually your question looks to be a duplicate of [Reading CSV files using C#](https://stackoverflow.com/q/3507498/3744182) unless you can be more specific about where you are stuck. Does your current code not work? Where do you need help? See [ask]. – dbc Apr 30 '22 at 19:54
  • The `IndexOf()` constraint means you are unlikely to get a good answer here, because no self-respecting developer would ever use `IndexOf()` for this when there are perfectly good CSV parsers available on NuGet or built into C#/.Net already. If nothing else we'd use `Split()`, and even that is pushing it. – Joel Coehoorn May 02 '22 at 13:34
  • I have found a lot of information that through "strLine = sr.ReadLine()) != null", you can accurately traverse the elements in the collection and then output through the output stream. Many materials do this – Housheng-MSFT May 05 '22 at 09:23

2 Answers2

0

I think you made a little bit of confusion between line and values. line contains the actual line, values contains the separated values of the single line. You have to read the line once for each loop iteration. Try the code blelow

// constant variables
const string INPUT_FILE = "input.txt";
const string OUTPUT_FILE = "output.txt";

// open the input file
StreamReader sr = new StreamReader(INPUT_FILE);

// fields used for input file
string? line = "";

string firstName = "", lastName = "";
double mark = 0;

// variables for calculating average
double total = 0, count = 0, avg = 0;

// continue to read until you reach end of file


while (!sr.EndOfStream)
{
    // read the first line of text from the input file
    line = sr.ReadLine();

    if (line != null)
    {
        string[] values = line.Split(',');
        if (values.Count() == 3)
        {
            firstName = values[0];
            lastName = values[1];
            mark = double.Parse(values[2]);
            total += mark;
            count++;
        }
    }
}
//close input file
sr.Close();

avg = total / count;
Console.WriteLine("\nClass Average: " + avg);

// open an output file
StreamWriter sw = new StreamWriter(OUTPUT_FILE);

sw.WriteLine(avg);

sw.Close();
Marco Beninca
  • 605
  • 4
  • 15
0

You can wrap code that reads and writes "IO" with a "try...catch" block so that if there is an error in the program, it can be resolved.

    static void Main(string[] args)
    {
        Test();
    }

    public static void Test () 
    {
        try
        {
            // constant variables
            const string INPUT_FILE = "input.txt";
            const string OUTPUT_FILE = "output.txt";

            // open the input file
            StreamReader sr = new StreamReader(INPUT_FILE);

            // fields used for input file
            string? line = "";

            string firstName = "", lastName = "";
            double mark = 0;

            // variables for calculating average
            double total = 0, count = 0, avg = 0;

            // continue to read until you reach end of file

            while ((line = sr.ReadLine()) != null)
            {
                string[] values = line.Split(',');
                firstName = values[0];
                lastName = values[1];
                mark = double.Parse(values[2]);
                count++;

            }

            //close input file
            sr.Close();

            avg = total / count;
            Console.WriteLine("\nClass Average: " + avg);

            // open an output file
            StreamWriter sw = new StreamWriter(OUTPUT_FILE);

            sw.WriteLine(avg);

            sw.Flush();

            sw.Close();
        }catch (Exception ex)
        {
             Console.WriteLine(ex.ToString());
        }
     
    }
Housheng-MSFT
  • 1
  • 1
  • 1
  • 9