且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

卡在2D数组上,将指针插入文件中的字符串

更新时间:2023-11-07 11:01:40

以下建议的代码:

  1. 干净地编译
  2. 执行OP的隐含功能
  3. (大部分)魔术"数字用有意义的名称替换
  4. 消除未使用/不需要的局部变量和不需要的逻辑
  5. 格式化代码,以易于阅读和理解
  6. 正确地将错误消息(以及操作系统认为发生错误的原因)输出到stderr
  7. 正确声明一个不接收任何参数的子函数的原型
  1. cleanly compiles
  2. performs the OPs implied functionality
  3. replaces (most) of the 'magic' numbers with meaningful names
  4. eliminates unused/unneeded local variables and unneeded logic
  5. formats the code for ease of readability and understanding
  6. properly outputs the error message (and the reason the OS thinks the error occurred) to stderr
  7. properly declares a prototype for a sub function that receives no parameters

现在,建议的代码:

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

#define MAX_ROW_LEN      1024
#define MAX_LINES        50
#define MAX_QUESTION_LEN 255
#define MAX_ANSWER_LEN   255

void readfromfile( void ); // func prototype

char data[ MAX_ROW_LEN ]; // a row from the file


//Fragebezogen
char id[ MAX_LINES ][5]; // question nr
char frageinhalt[ MAX_LINES ][ MAX_QUESTION_LEN ]; // the question itself (later smth like "capital of germany?"
char antw1[ MAX_LINES ][ MAX_ANSWER_LEN ]; // the first answer to the question
char antw2[ MAX_LINES ][ MAX_ANSWER_LEN ]; // second answ


int main( void )
{
    readfromfile();
    printf("\nFrageinhalt: %s Antw1: %s Antw2: %s\n",
            frageinhalt[1],
            antw1[1],
            antw2[1]);
    return 0;
}


void readfromfile()
{
    FILE *datei_ptr;
    char delimiter[] = ",;#";
    char *token;

    datei_ptr = fopen("test.txt", "r");

    if ( !datei_ptr )
    {
        perror( "fopen failed" );
        exit( EXIT_FAILURE );
    }

    int lineCounter = 0;
    while( lineCounter < MAX_LINES && fgets (data, sizeof( data ), datei_ptr) )
    {
        puts(data);
        printf("###############################\n");

        token = strtok(data, delimiter);

        if ( token )
        {
            printf("Abschnitt gefunden: %s\n", token);
            strncpy( id[ lineCounter ], token, 5 );

            token = strtok(NULL, delimiter);
            if( token )
            {
                strncpy( frageinhalt[ lineCounter ], token, MAX_QUESTION_LEN );

                token = strtok( NULL, delimiter );
                if( token )
                {
                    strncpy( antw1[ lineCounter ], token, MAX_ANSWER_LEN );

                    token = strtok( NULL, delimiter );
                    if( token )
                    {
                        strncpy( antw2[ lineCounter ], token, MAX_ANSWER_LEN );
                    }
                }
            }
        }

        printf("###############################\n");
        lineCounter++;
    }

    fclose(datei_ptr);
}