gpt4 book ai didi

c - 此方法是否返回 int Nrows 和 int Ncols?

转载 作者:行者123 更新时间:2023-11-30 21:00:22 24 4
gpt4 key购买 nike

我对 C 编程完全陌生(只做 java),这些语句的不同足以让我感到困惑。我想知道我的方法头是否声明我需要在方法内声明 Nrows 和 Ncols (来 self 的主方法)?只需将它们设置为某个变量就足够了吗?

#include <stdio.h>

void RdSize(int *Nrows, int *Ncols)
{
Nrows = NULL;
Ncols = NULL;
FILE *in = fopen("A1in.txt","r");
if(in == NULL) { perror("Error opening file");}
else
{
int i;
char input[4]; //I have no idea how to set the size of the array to
//the length of the first line of the input file
//(which has 4 chars, but is not optimal to put the
//number 4)

for(i = 0; i < sizeof(input); i++)
{
input[i] = fgetc(in); //trying to copy each char into input[]
//array

if(isdigit(input[i]) && Nrows == NULL)
{
Nrows = input[i] - '0'; //converting from char to int
} //Here I'm setting Nrows to
//something. Is this all I do?
if(isdigit(input[i]) && Nrows != NULL)
{
Ncols = input[i] - '0'; //converting from char to int
} //setting Ncols
}
}
fclose(in);
}

此外,如果我有一个如下所示的 .txt 文档:

0 0 0 0 0 0 0 
0 1 0 1 0 1 0
0 1 1 1 0 1 0
0 1 0 1 0 1 0
0 0 0 0 0 0 0

将其从 .txt 文件放入二维字符数组的最佳方法是什么?

非常感谢!

最佳答案

要从文件的第一行读取两个数字,您只需使用 fscanf() 代替循环即可。

void RdSize(int *Nrows, int *Ncols)
{
FILE *in = fopen("A1in.txt","r");
if(in == NULL) {
perror("Error opening file");
return;
}
if (fscanf(in, "%d %d", Nrows, Ncols) != 2) {
printf("Error reading size\n");
}
fclose(in);
}

%d 表示解析文件中的一个整数。这些数字被写入 NrowsNcols 指向的内存,它们是调用者的变量。

关于c - 此方法是否返回 int Nrows 和 int Ncols?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41885829/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com