卡在2D数组上,将指针插入文件中的字符串 [英] Stuck on 2D Arrays, inserting a pointer into a string from a file

查看:85
本文介绍了卡在2D数组上,将指针插入文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

修改:使用普通c

这部分地是指我的最后一个问题,但是我现在完全重写了大约3次代码,而现在我陷入了严重的困境.我已经读过很多关于2D数组的东西,我感到困惑,因为我应该认为是正确的,其他stackoverflow帖子使我更加困惑:(

this partly refers to my last question, but i completely rewrote the code for around 3 times now and I'm in a major rut. I've read so many different things about 2D arrays, I'm confused as what i should deem as right, other stackoverflow posts confuse me even more :(

例如:

char array[A][B];

一些消息来源说A是nr.字段的长度,B表示一个字段的长度,而其他字段则说A是nr.行,B为nr.矩阵的列数.其他人则说这只会节省单个字符.

Some sources say that A is the nr. of fields and B the length of one field, while others say that A is the nr. of rows and B the nr. of columns of a matrix. Others say that this only saves single chars.

继续解决我的问题:

我正在写一个测验,并且我有一个数据库文件,其中每一行都是这样的:

I'm writing a Quiz, and I've got a databasefile in which each row looks like this:

Multiple Words A#Multiple Words B#Multiple Words C

现在,我想读取文件并将该行拆分为多个变量,这些变量的定义如下:

Now I want to read the file and split the line into multiple variables, which are defined like this:

char frageinhalt[50][255]; // the question itself (later smth like "capital of germany?"
char antw1[50][255]; // the first answer to the question
char antw2[50][255]; // second answ

行应该这样分割:

Multiple Words A => frageinhalt
Multiple Words B => antw1
Multiple Words C => antw2

每行应该在数组中获得分配的字段,因此我可以简单地在其他函数中打印它们.

each row should get an assigned field in the arrays, so I can simply print them in other functions.

例如: 我想打印第一个问题及其答案

For example: I want to print the first question and it's answers

printf("%s,%s,%s",frageinhalt[0],antw1[0],antw2[0]);

但这在我的代码中不起作用.有什么主意吗?

But that doesn't work in my code. Any idea?

下面的完整代码.

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

int readfromfile(); // func prototype

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

char temp[50];

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


int main() {
  readfromfile();
  printf("\nFrageinhalt: %s Antw1: %s Antw2: %s\n", frageinhalt[1], antw1[1], antw2[1]); // Doesn't work properly
  return 0;
}
int readfromfile() {
  FILE *datei_ptr;
  int i = 0;
  char ch;
  int lines = 0;
  int k = 0;
  char delimiter[] = ",;#";
  char *ptr;


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

  if (datei_ptr == NULL) {
    printf("nothing left in file");



 }
  else {

while (!feof(datei_ptr))
{
  ch = fgetc(datei_ptr);
  if (ch == '\n') // Wenn der gerade gelesene Character ein Zeilenumbruch ist..
  {
    lines++; // Erhöhe die Anzahl der Zeilen um 1
  }
}

fclose(datei_ptr);
datei_ptr = fopen("test.txt", "r");
do {
  fgets (data, 255, datei_ptr);
  puts(data);


  ptr = strtok(data, delimiter);
  printf("###############################\n");
  while (ptr != NULL)
  {

    printf("Abschnitt gefunden: %s\n", ptr);

    // naechsten Abschnitt erstellen
    ptr = strtok(NULL, delimiter);
  }
  printf("###############################\n");
  k++;
} while (k != lines + 1);

fclose(datei_ptr);
  }

}

推荐答案

以下建议的代码:

  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);
}

这篇关于卡在2D数组上,将指针插入文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆