Как читать параметры из текстового файла в C - PullRequest
0 голосов
/ 04 мая 2018

Мне дали задание прочитать параметры из текстового файла и создать матрицу из этих параметров. Я часами застрял на той части, где читаю цифры. Порядок, в котором они организованы в тестовом файле, таков:

Число Число Число Буква (L или S)

И еще одна строка с такой же структурой.

Мой код до сих пор таков:

#include <stdio.h>
#include <stdlib.h>

typedef struct matrix {//create a struct of matrix
    int** mat;//the name
    int rows, cols, start;//How many rows and cols + starting number
    char shape;// The shape of the matrix
}matrix;


int** createMat(int r, int c);//Signature of a function #1
int strToInt(char* str);//Signature of a function #2
int CheckName(char A[], char B[]);//Signature of a function #3


int main(int argc, char** argv)//start of the program
{
    matrix mat;//create a matrix
    int lines = 0;//get the number of lines
    FILE* input;//Create a pointer
    char temp[5];//Create a temporary array
    if (argc > 3 || argc < 2)//Check if the number of the parameters is     correct
    {
        printf("There's a wrong number of arguments. Please try again.");
    }
    else
    {
        if (CheckName(argv[1], "input.txt") == 0)//check if the parameter is input.txt
        {
            if (argc == 3)//Check if the third parameter is given.
            {
                lines = strToInt(argv[2]);//fill the number of lines with the number of the lines
            }
            input = fopen(argv[1], "R");//open and read the input file
        }
    }
    return 0;
}

int** createMat(int r, int c)//creat a matrix function
{
    int *arr = (int *)malloc(r * c * sizeof(int));
    return arr;
}

int strToInt(char* str)//insted of atoi function
{
    return atoi(str);
}

int GetNumber(FILE* file)//Get the number function
{
    char ch;//Create a temporary file
    int len;//Create a temporary file
    char temp[5];//Create a temporary array
    while ((ch = fgetc(file)) != ' ')
    {
        len = strlen(temp);
        temp[len] = ch;
        temp[len + 1] = 0;
    }


int CheckName(char A[], char B[])
{
    int result = 1;
    for (int i = 0; A[i] || B[i]; i++)
    {
        if (A[i] != B[i])
        result = 0;
    }
    return result;
}

1 Ответ

0 голосов
/ 04 мая 2018

Похоже, вы знаете, что в каждой строке эти элементы разделены пробелами.

Тогда вы можете просто разбить каждую строку на токены. Посмотрите на ответ на этот вопрос:

Разделить строку в C через каждые пробелы

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