Как читать символы из txt файла в 2d массив C ++

0

Итак, у меня есть файл, в котором есть команды и оценки, мне нужно прочитать команду в 2D-массив символов, а затем их оценку в массив ints.

Это мой текущий код для моей функции, как мне заставить это перестать читать после того, как имя команды будет заполнено, а затем сохранить оценку в отдельном массиве?

void getData (char array [][COLS], int rows, int scores [])
{
    ifstream inFile;     //Input file stream object

    //Open the file
    inFile.open ("scores.txt");

     if (!inFile)
    {
        cout << "Error opening data file!\n";
        exit(102);
    }

    for (int r = 0; r < rows; r++)
    {
        {
            //reads through columns
            for (int c = 0; c < COLS; c++)
            {
                inFile >> array[r][c];
            }
        }
    }

    for (int count = 0; count < ROWS; count++)
    {
        for(int i = 0; i < COLS; i++)
        {
            cout << array[count][i];
        }
    }

    inFile.close();
}

Мой входной файл выглядит следующим образом:

Jaquars 23
Colts 23
49ers 13
Lions 13
Titans 7
Redskins 38
Cardinals 14
Buccaneers 36
Seahawks 30
Lions 24
Bears 28
Packers 23
Bears 14
Rams 22
Texans 6
Packers 34
Теги:
arrays
file
char
2d

3 ответа

0
Лучший ответ

Может быть, так

for (int r = 0; r < rows; r++)
{
    int c = 0;
    // keep reading until we hit a space
    char ch = inFile.get();
    while (ch != ' ')
    {
        array[r][c] = ch;
        c++;
        ch = inFile.get();
    }
    // now read the score
    inFile >> scores[r];
    // now read until we hit the trailing newline
    ch = infile.get();
    while (ch != '\n')
    {
        ch = inFile.get();
    }
}
  • 0
    Jaquars 23 Colts 23 49ers 13 Львы 13 Titans 7 Redskins 38 Кардиналы 14 Buccaneers 36 Seahawks 30 Львы 24 Медведи 28 Packers 23 Медведи 14 баранов 22 Texans 6 Packers 34 Это мой файл, все из которых находятся на отдельных линиях
  • 0
    Хорошо, мой ответ выше совершенно неверен. Я бы поставил эту информацию в вопрос выше, чтобы все ее увидели (и попробовали правильно отформатировать).
Показать ещё 11 комментариев
0

Это то, что у меня есть для моего кода

void getData (char array [][COLS], int rows, int scores [])
{
     ifstream inFile;     //Input file stream object

    //Open the file
    inFile.open ("scores.txt");

     if (!inFile)
    {
        cout << "Error opening data file!\n";
        exit(102);
    }

for (int r = 0; r < rows; r++)
{
    int c = 0;
    char ch;
    // keep reading until we hit a space
    ch = inFile.get();
    while (ch != ' ')
    {
        array[r][c] = ch;
        c++;
        ch = inFile.get();
    }
    // now read the score
    inFile >> scores[r];
    // now read until we hit the trailing newline
    ch = inFile.get();
    while (ch != '\n' && ch != EOF)
    {
        ch = inFile.get();

    }
}

        for (int count = 0; count < rows; count++)
        {
            for(int i = 0; i < COLS; i++)
            {
                cout << array[count][i];
                for (int count2 = 0; count2 < rows; count2++)
                    cout << scores[count2];
            }
        }

    inFile.close();

    return;
}
0

Это должно дать вам представление о том, как это сделать. Я не скомпилировал его. Но это послужит хорошим примером. Я настоятельно рекомендую вам перейти на решение на основе карты. Или используйте векторы.

#include <string>
#include <iostream>
#include <fstream>
#include<cstring>
#include<cstdlib>
using namespace std;

int main() 
{   
    ifstream in("DataFile.txt");
    string line;
    char * pch;

    while(getline(in, line))
    {
        pch = strtok (line.c_str()," ");
        while (pch != NULL)
        {
            //Put some logic here so that in first loop iteration
            //first segment(name) gets stored in your char arrays.
            //In second iteration, which will return the score, you store that
            //in the int array. Do not forget to use atoi() to convert to int before storing.
            pch = strtok (NULL," ");
        }
    }

    //There are more elegant ways to split a string in C++
    //http://stackoverflow.com/questions/236129/how-to-split-a-string-in-c
    return 1;
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню