我需要将一个字符串(来自一个文件)放入一个矩阵中并打印出结果。我在理解这样做的正确方法时遇到了一些问题:
#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;
}
我显然做错了什么,但是……什么?
我有这样一个文件:
One
Two
Three
Four
Five
Six
Hello
最佳答案
如果你用 gcc
编译它,它会给你两个警告:每个警告都指向代码中的三个主要错误之一:
main.c: In function 'main':
main.c:24: warning: passing argument 1 of 'strcpy' makes pointer from integer without a cast
main.c:31: warning: passing argument 1 of 'puts' makes pointer from integer without a cast
每个行号——24 和 31——都是你使用 mat[i][0]
的行,它是一个字符,而你应该使用 mat[i]
,这是一个字符数组。解决这些问题,然后就会出现一个问题:您在 while
循环中使用 i
,它始终为 0。使用 row
,它随着行的进行而递增,程序应该完全按照设计工作。
为了改进程序,我还要做其他一些更改:while
循环将一个字符串读入一个缓冲区,将其复制到第二个缓冲区,然后将其复制到矩阵中;您只需将其直接扫描到矩阵中即可完成!
关于c - 将字符串放入C中的矩阵中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11795284/