edit: using plain c
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 :(
For example:
char array[A][B];
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.
Going on to my problem:
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
The rows should be split up like this:
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?
Full code below.
#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);
}
}