I need to put a string (from a file) in a matrix and print out the result. I have some issue in understanding the right way to do this so:
#include <stdio.h>
#include <string.h>
int main (int argc, char *argv[])
{
const int MAX = 50;
char mat[MAX][MAX];
char str[MAX];
char word[MAX];
int row = 0;
int i = 0;
FILE * fp;
fp = fopen ("file.txt", "r");
if (fp == NULL)
printf ("Error!\n");
while (fgets(str, MAX, fp) != NULL)
{
sscanf (str, "%s\n", word);
strcpy(mat[i][0], word);
row++;
}
for (i = 0; i <= row; i++)
{
puts(mat[i][0]);
}
return 0;
}
I’m obliviously doing something wrong but… what?
I have a file like this:
One
Two
Three
Four
Five
Six
Hello
If you compile this with
gcc, it will give you two warnings: each warning points to one of the three major errors in the code:Each of those line numbers — 24 and 31 — is a line where you’re using
mat[i][0], which is a character, when you should instead usemat[i], which is a character array. Fix those, and then there’s just one problem: you usei, which is always 0, in thewhileloop. Userow, which is incremented as the row progresses, and the program should work exactly as designed.There are a couple of other things I would change to improve the program: your
whileloop reads a string into one buffer, copies it into a second buffer, then copies it into the matrix; you could just scan it directly into the matrix and be done with it!