Почему даже при использовании for l oop для перебора моего вектора он не выводится на консоль? (C ++) - PullRequest
0 голосов
/ 17 июня 2020

Это беспорядочно, потому что я новичок в C ++. Я сделал функцию, которая возвращает значение вектора, получая его элементы из файла .txt. Я сделал отдельные векторы для сортировки, но это не имеет отношения к этому вопросу.

vector<string> txtToArr(int c) {
    ifstream unList;
    unList.open("unorderedList");
    vector<string> names;
    vector<double> times;
    vector<int> bNum;
    string tempS;
    double tempD;
    int tempI;

    // Adds data to their respective vectors
    int count = 0;
    while (!unList.eof()) {
        if (count == 1) {
            unList >> tempS;
            names.push_back(tempS);
        }
        else if (count == 2) {
            unList >> tempD;
            times.push_back(tempD);
        }
        else if (count == 3) {
            unList >> tempI;
            bNum.push_back(tempI);
            count = -1;
        }
        count++;
    }

    int small;
    string temp;
    double temp2;
    int temp3;

    // Sorts vectors using selection sort
    for (int i = 0; i < c - 1; i++) {
        small = i;
        for (int j = i + 1; j < c; j++) {
            if (times[j] < times[small]) {
                small = j;
            }
        }
        temp = names[i];
        temp2 = times[i];
        temp3 = bNum[i];
        times[i] = times[small];
        names[i] = names[small];
        bNum[i] = bNum[small];
        names[small] = temp;
        times[small] = temp2;
        bNum[small] = temp3;
    }

    // Compiles all of the vectors together
    vector<string> all;
    for (unsigned int i = 0; i < names.size(); i++) {
        all.push_back(to_string(i+1));
        all.push_back(names[i]);
        all.push_back(to_string(times[i]));
        all.push_back(to_string(bNum[i]));
    }

    unList.close();
    return all;
}


Затем я попытался вывести его на консоль, используя следующее:

        // Outputs vectors (This is in the main btw)
        int count2 = 0;
        for (unsigned int i = 0; i < txtToArr(count).size(); i++) {
            if (count2 == 3) {
                cout << "\n";
                count2 = -1;
            }
            cout << txtToArr(count).at(i) << " ";
            count2++;
        }

Но по какой-то причине он не будет выводиться на консоль. Я уверен, что это небольшая ошибка, но я не могу ее найти.

Спасибо за вашу помощь!

Вот полный код, если это помогает:

// This program takes your name and your fastest 5k(running) times. It puts that data in a .txt file, and reads that data.
// It then outputs a ranking compared to other people entered in and displays a randomly generated bib or racing number.

#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstdlib>
#include <string>
#include <vector>

using namespace std;

// Generates random bib number between 1 and 100
int bibNum() {
    return rand() % 100 + 1;
}

vector<string> txtToArr(int c) {
    ifstream unList;
    unList.open("unorderedList");
    vector<string> names;
    vector<double> times;
    vector<int> bNum;
    string tempS;
    double tempD;
    int tempI;

    // Adds data to their respective vectors
    int count = 0;
    while (!unList.eof()) {
        if (count == 1) {
            unList >> tempS;
            names.push_back(tempS);
        }
        else if (count == 2) {
            unList >> tempD;
            times.push_back(tempD);
        }
        else if (count == 3) {
            unList >> tempI;
            bNum.push_back(tempI);
            count = -1;
        }
        count++;
    }

    int small;
    string temp;
    double temp2;
    int temp3;

    // Sorts vectors using selection sort
    for (int i = 0; i < c - 1; i++) {
        small = i;
        for (int j = i + 1; j < c; j++) {
            if (times[j] < times[small]) {
                small = j;
            }
        }
        temp = names[i];
        temp2 = times[i];
        temp3 = bNum[i];
        times[i] = times[small];
        names[i] = names[small];
        bNum[i] = bNum[small];
        names[small] = temp;
        times[small] = temp2;
        bNum[small] = temp3;
    }

    // Compiles all of the vectors together
    vector<string> all;
    for (unsigned int i = 0; i < names.size(); i++) {
        all.push_back(to_string(i+1));
        all.push_back(names[i]);
        all.push_back(to_string(times[i]));
        all.push_back(to_string(bNum[i]));
    }

    unList.close();
    return all;
}

int main()
{
    // Only prints out 2 digits after the decimal
    cout << setprecision(2) << fixed;

    // Variables
    string name;
    double PR;
    int input;
    int count = 0;
    ofstream unorderedList;
    unorderedList.open("unorderedList.txt");

    cout << "This program takes your name and your fastest 5k(running) times.\nIt puts that data in a .txt file, and reads that\ndata. It then outputs a ranking compared to other people entered\nin and displays a randomly generated bib or racing number.\n\n";
    do {
        count++;
        unorderedList << count << " ";
        cout << "Enter your name: ";
        cin >> name;
        unorderedList << name << " ";

        cout << "\n\nEnter in your fastest 5k. For example 17:41 = 17.41: ";
        cin >> PR;
        unorderedList << PR << " " << bibNum() << "\n";
        cout << "1 to continue entering times / 2 to see the data";
        cin >> input;


    } while (input == 1);

    if (input == 2) {
        // Outputs vectors
        int count2 = 0;
        for (unsigned int i = 0; i < txtToArr(count).size(); i++) {
            if (count2 == 3) {
                cout << "\n";
                count2 = -1;
            }
            cout << txtToArr(count).at(i) << " ";
            count2++;
        }
        exit(0);
    }

}

Ответы [ 2 ]

0 голосов
/ 17 июня 2020
  1. Когда вы устанавливаете входной файл, вам необходимо добавить расширение .txt, поэтому "unorderedList.txt"

  2. Закройте выходной файл перед открытием входа файла, это можно сделать с помощью unorderedList.close ()

  3. Я настоятельно рекомендую вам изменить способ чтения вводимого файла, поскольку в настоящее время вы бесконечно зацикливаетесь на while (! unList. eof ()) l oop не завершается. Я бы посоветовал следовать руководству по этой ссылке: http://www.cplusplus.com/doc/tutorial/files/ или используя строку получения стиля C, следующая ссылка содержит отличный пример того, как это сделать: C строка чтения файла по строке

Надеюсь, это поможет.

0 голосов
/ 17 июня 2020

Первое, что нужно проверить: есть ли в "unorderedList.txt" какие-либо данные. Это легко проверить с помощью текстового редактора. Нет, это не так, потому что вы забыли закрыть его после завершения записи данных.

Также следующий l oop читает файл каждые l oop.

for (unsigned int i = 0; i < txtToArr(count).size(); i++) {

Это странно. Рассмотрите возможность сохранения его в переменной и повторного использования. Например,

vector<string> data = txtToArr(count);
for (unsigned int i = 0; i < data.size(); i++) {
...