首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

fscanf函数有关问题

2012-03-12 
fscanf函数问题请问哪位大侠给小弟指点一下,fscanf()在c语言中,如何从文件中读字符串到数组中啊(有多行文

fscanf函数问题
请问哪位大侠给小弟指点一下,fscanf()在c语言中,如何从文件中读字符串到数组中啊(有多行文件)。
整型数我会字符串就出错不知为何!
小弟初学,谢了。

[解决办法]
int fscanf( FILE *stream, const char *format [, argument ]... );


#include <stdio.h>

FILE *stream;

void main( void )
{
long l;
float fp;
char s[81];
char c;

stream = fopen( "fscanf.out", "w+" );
if( stream == NULL )
printf( "The file fscanf.out was not opened\n" );
else
{
fprintf( stream, "%s %ld %f%c", "a-string", 
65000, 3.14159, 'x' );

/* Set pointer to beginning of file: */
fseek( stream, 0L, SEEK_SET );

/* Read data back from file: */
fscanf( stream, "%s", s );
fscanf( stream, "%ld", &l );

fscanf( stream, "%f", &fp );
fscanf( stream, "%c", &c );

/* Output data read: */
printf( "%s\n", s );
printf( "%ld\n", l );
printf( "%f\n", fp );
printf( "%c\n", c );

fclose( stream );
}
}

[解决办法]

C/C++ code
int main(int argc, char *argv[]){  FILE *in;  char *str[10] = {NULL};  int i = 0;  if((in = fopen("1.txt", "r")) == NULL){         printf("file open failed.");                return 1;  }  while(!feof(in)){         str[i] = (char*)malloc(100);         fscanf(in, "%s", str[i]);           ++i;          }  i = 0;  while(str[i] != NULL){         printf("%s", str[i]);                      free(str[i]);         ++i;  }  system("pause");  return 0;}
[解决办法]
fgets()应该就是读一行的吧
用法:
fgets(char * s,int size,FILE * stream);
[解决办法]
你的字符串中间不能有空白字符,否则,用fgets好一些
[解决办法]
用fscanf()读一行字符串有很多不方便之处,
很麻烦而且还容易出错,
楼主还是用fgets()吧,这个函数是专门用于读取一行代码的,
有更加"专业"的 fgets()为什么非要用fscanf()呢??

查一下fgets() 的用法(网上很多)
我保证,这个函数肯定是你想要的答案.

[解决办法]
呵呵,要读整行还不简单那,直接fgets()就OK了.
函数名: fgets 
功 能: 从流中读取一字符串 
用 法: char *fgets(char *string, int n, FILE *stream); 
程序例: 

C/C++ code
#include <string.h> #include <stdio.h> int main(void) {    FILE *stream;    char string[] = "This is a test";    char msg[20];    /* open a file for update */    stream = fopen("DUMMY.FIL", "w+");    /* write a string into the file */    fwrite(string, strlen(string), 1, stream);    /* seek to the start of the file */    fseek(stream, 0, SEEK_SET);    /* read a string from the file */    fgets(msg, strlen(string)+1, stream);    /* display the string */    printf("%s", msg);    fclose(stream);    return 0; } 

热点排行