文件看起来像这样:
trying to read this file#*)will it work?
每当我尝试阅读
string
和string2
时,都会有一些垃圾;我猜我的sscanf
是错误的:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[100];
char string[100];
char string2[100];
FILE *ptr = fopen ("testing8.txt", "r");
if ((ptr = fopen("testing8.txt", "r"))!= NULL )
printf("file opened successfuly\ncontinuing program..\n");
else
{
printf("unable to open file, terminating program\n");
return 0;
}
fgets(buffer, 50, ptr);
//testing to see whether string contains the string or not..
printf("%s\n",buffer);
sscanf(ptr,"%[^#*)]#*)%[^?]?", string, string2);
puts(string);
puts("\n");
puts(string2);
puts("\n");
fclose(ptr);
return 0;
}
最佳答案
如果您尝试编译代码版本,则应收到警告
$gcc so_test2.c
so_test2.c: In function ‘main’:
so_test2.c:28: warning: passing argument 1 of ‘sscanf’ from incompatible pointer type
/usr/include/stdio.h:452: note: expected ‘const char * __restrict__’ but argument is of type ‘struct FILE *’
$
因此,我进行了以下更改。这对我有用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char buffer[100];
char string[100];
char string2[100];
FILE *ptr;//fopen ("testing8.txt", "r");
if ((ptr = fopen("testing8.txt", "r"))!= NULL )
printf("file opened successfuly\ncontinuing program..\n");
else
{
printf("unable to open file, terminating program\n");
return 0;
}
if (fgets(buffer, 50, ptr) == NULL) //added check for success of fgets()
{
printf("fgets error\n");
exit (-1);
}
//testing to see whether string contains the string or not..
printf("%s\n",buffer);
sscanf(buffer,"%[^#*)]#*)%[^?]?", string, string2); //change ptr to buffer
puts(string);
puts("\n");
puts(string2);
puts("\n");
fclose(ptr);
return 0;
}
关于c - 为什么字符串不存储在各自的数组中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20937831/