我需要一种方法来获取每个输入字符,并将它们放入一个二维数组(在本例中是一个char
数组).
但是,因为我需要从有几个行尾(\n
)的文件输入中获得这个字符,所以我不希望将这些行插入到数组中,所以我try 设置一个条件,如果字符是换行符,则不应该将其放入数组中,但它似乎不起作用.
我只是想说明一下,我正在try 自己制作这个方法,因为我在网上没有找到一个,而fgets
是我找到的最好的方法.
我的代码是:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]) {
char words[4][4][2];
char verif[2];
int i, j, l = 0, lin = 4, col = lin;
printf("Insert numbers: ");
for (i = 0; i < lin; i++)
{
for (j = 0; j < col; j++)
{
fgets(verif, 2, stdin);
//since I was using the IDE to write I also put a condition not to add the enter for the input but it doesn't work too lol
if (strcmp(verif, "\n\0") != 0 || strcmp(verif, "\r\0") != 0)
{
printf("copying...\n");
printf("%s\n", verif);
strcpy(words[i][j], verif);
l++;
}
else
j--;
}
}
printf("\n");
for (i = 0; i < lin; i++)
{
for (j = 0; j < col; j++)
{
printf("-%s\t", words[i][j]);
}
printf("\n");
}
return 0;
}
我将使用的输入放在矩阵中:
1234
1234
1234
1234
对于像1234123412341234
这样的正常输入,输出(打印矩阵)是正常的:
-1 -2 -3 -4
-1 -2 -3 -4
-1 -2 -3 -4
-1 -2 -3 -4