Работа с файлами, цикл не останавливается, где я хочу - PullRequest
0 голосов
/ 05 декабря 2018

В настоящее время я работаю над программой на C #, которая требует от меня написать программу, которая получает информацию о нескольких учениках, а затем сохраняет введенные данные в два файла: текстовый файл и двоичный файл.Напишите вашу программу так, чтобы при ее запуске программа запрашивала у пользователя количество учащихся, которое предполагается ввести, а затем программа запрашивает данные (имя студента, рост студента, вес студента) о том, что любое количество студентовПосле ввода данные сохраняются в два файла: один текстовый файл и один двоичный файл.Моя проблема сейчас заключается в том, что всякий раз, когда я запускаю цикл, он не останавливается там, где я хочу, и это количество, которое пользователь вводит в начале.Если у вас есть какая-либо помощь, пожалуйста, не стесняйтесь комментировать.Благодарю.Вот код:

using System;
using static System.Console;
using System.IO;

namespace BinaryAssignment
{
    class Program
    {
        static void Main(string[] args)
        {
            StreamWriter outputFile;
            FileStream fsOutput = new FileStream("outFile.bin", FileMode.Create);
            BinaryWriter myOutputFile = new BinaryWriter(fsOutput);
            outputFile = new StreamWriter("ex1.txt");
            outputFile = new StreamWriter("ex1.bin");
            double studentAmount ;
            string studentName;
            int studentHeight;
            double studentWeight;

            Write("Data of how many students do you want to enter? ");
            studentAmount = double.Parse(ReadLine());

            double x = 0;
            do
            {
                Write("Enter the name of the student: ");
                studentName = ReadLine();
                myOutputFile.Write(studentName);
                outputFile.WriteLine(studentName);

                Write("Enter the height of the student in centimeters: ");
                studentHeight = int.Parse(ReadLine());
                outputFile.WriteLine(studentHeight);
                myOutputFile.Write(studentHeight);

                Write("Enter the weight of the student in kilograms: ");
                studentWeight = double.Parse(ReadLine());
                outputFile.WriteLine(studentWeight);
                myOutputFile.Write(studentWeight);

            } while ((x = studentAmount) >= 0);

            outputFile.Close();
            Console.ReadKey();





        }
    }
}

Ответы [ 3 ]

0 голосов
/ 05 декабря 2018

Добро пожаловать в Кевин.Похоже, вы только изучаете программирование.Как уже упоминалось Pm100;вы попадаете в цикл под названием Infinite Loop.Для вашего решения просто замените эти строки.

    double x = 0;
        do
        {
            .....
            x=x+1;  //Add this line
        } while (x < studentAmount);  //Change the condition like this
0 голосов
/ 05 декабря 2018

Кевин - Код, который вы разместили, не будет работать как есть - вы забыли «Консоль».до чтения / записи.Вы также должны проверить входные данные - но ваша конкретная проблема заключалась в том, что вы не прерывали цикл.Пожалуйста, смотрите комментарии в коде ниже:

    static void Main(string[] args)
    {
        StreamWriter outputFile;
        FileStream fsOutput = new FileStream("outFile.bin", FileMode.Create);
        BinaryWriter myOutputFile = new BinaryWriter(fsOutput);
        outputFile = new StreamWriter("ex1.txt");
        outputFile = new StreamWriter("ex1.bin");
        int studentAmount;      // This should be an int not double
        string studentName;
        int studentHeight;
        double studentWeight;

        Console.Write("Data of how many students do you want to enter? ");

        // You should validate the input using the appropriate TryParse
        var input = Console.ReadLine();
        if (!int.TryParse(input, out studentAmount))
        {
            // You need to append 'Console.' to the beginning of the read/write operations
            Console.WriteLine("You entered an invalid number for  student amounnt - ending...");
            Console.ReadKey();
            return;
        }

        // double x = 0;    // You don't need this variable
        do
        {
            Console.Write("Enter the name of the student: ");
            studentName = Console.ReadLine();
            myOutputFile.Write(studentName);
            outputFile.WriteLine(studentName);

            Console.Write("Enter the height of the student in centimeters: ");
            input = Console.ReadLine();
            if (!int.TryParse(input, out studentHeight))
            {
                Console.WriteLine("You entered an invalid number for  height - ending...");
                Console.ReadKey();
                return; 
            }
            outputFile.WriteLine(studentHeight);
            myOutputFile.Write(studentHeight);
            Console.Write("Enter the weight of the student in kilograms: ");
            input = Console.ReadLine();
            if (!double.TryParse(input, out studentWeight))
            {
                Console.WriteLine("You entered an invalid number for weight - ending...");
                Console.ReadKey();
            }
            outputFile.WriteLine(studentWeight);
            myOutputFile.Write(studentWeight);

            // You need to decrement your counter so you don't loop forever
        } while (--studentAmount > 0);

        outputFile.Close();
        Console.ReadKey();
    }
0 голосов
/ 05 декабря 2018

цикл прерывается, когда это больше не соответствует действительности

while ((x = studentAmount) >= 0);

Вы никогда не меняете studentAmount, поэтому цикл будет работать вечно

вам нужно studentAmount-- где-то

Проще и понятнее было бы

for(int i = 0; i < studentAmount; i++)
{
   .....
}

вместо цикла do / while

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...