我在读取文件时遇到问题,循环外的第一次打印正确完成。但在 for 循环中,没有从文件中读取任何内容。如果有人知道发生了什么,我正在寻找解释或帮助。(假设文件中有 n*m 个字符串,以“\t\r\n”分隔)谢谢。
{
char *file_name{
char *new_num=" ";
FILE *ifp=NULL;
int i, j, n, m;
ifp =fopen(file_name,"r");
if (ifp!=NULL)
{
fscanf(ifp,"%d %d",&n,&m );
printf("\n Data from the file: %d, %d \n",n,m);
}
for (i=0 ; i< n ;i++){
for(j=0;j<m;j++){
fscanf(ifp,"%s",new_num);
printf("\n new num : %s ",new_num);
}}
fclose(ifp);
return 0;
}
为了将某些内容读入变量或指针,您应该分配空间。
char *new_num=" ";
在这里,它在文本段中写入字符串并将该指针指向 new_num。
我对你的代码做了一些改动
#include <stdio.h>
#include <stdlib.h>
#define SIZE 50
int main()
{
char *file_name;
char new_num[SIZE];
FILE *ifp=NULL;
int i, j, n, m;
file_name = "input.txt";
ifp =fopen(file_name,"r");
if (ifp!=NULL)
{
fscanf(ifp,"%d %d",&n,&m );
printf("Data from the file: %d, %d \n",n,m);
}
for (i=0 ; i< n ;i++){
for(j=0;j<m;j++){
fscanf(ifp,"%s",new_num);
printf("new num : %s\n ",new_num);
}
}
fclose(ifp);
return 0;
}
通过将名称 new_num 解释为整数,我建议您使用 apt 数据类型而不是 %s
为此,您需要修改 new_num 的数据类型
type new_num[SIZE];
并在内部fscanf
使用 apt 标识符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句