sscanf 不兼容的指针类型
sscanf incompatible pointer types
所以我尝试使用 sscanf 函数读取一行的所有组件,如下所示:
char *R1;
char *R2;
int immediate;
char mnemonic[6];
FILE *input = fopen("file.txt","r");
...
sscanf(input, "%s %s %s %d", mnemonic, R1, R2, immediate);
编译时,出现以下警告:
Warning: passing argument 1 pf 'sscanf' from incompatible pointer type note: expected const char * restrict but argument is of type 'struct FILE *'
我怀疑此警告是我的代码无法按预期执行的原因,有人可以尝试解释问题所在吗?
如果您尝试从 FILE*
读取数据,您需要使用 fscanf
,而不是 sscanf
。后者从字符串 (char *
).
扫描
另外,%d
需要传入一个对应的int指针,否则fscanf
不能修改整数
此外,您正在传递未初始化的 char*
s - fscanf
将尝试将您的字符串写入某个未定义的地址。您需要像 mnemonic
.
那样给他们存储空间
最后,无论何时使用 %s
,您都应该明确地告诉它缓冲区的大小。否则很容易溢出。
char R1[6];
char R2[6];
int immediate;
char mnemonic[6];
FILE *input = fopen("file.txt","r");
...
if (fscanf(input,
"%6s %6s %6s %d", mnemonic, R1, R2, &immediate) != 4) {
// bad things happened
所以我尝试使用 sscanf 函数读取一行的所有组件,如下所示:
char *R1;
char *R2;
int immediate;
char mnemonic[6];
FILE *input = fopen("file.txt","r");
...
sscanf(input, "%s %s %s %d", mnemonic, R1, R2, immediate);
编译时,出现以下警告:
Warning: passing argument 1 pf 'sscanf' from incompatible pointer type note: expected const char * restrict but argument is of type 'struct FILE *'
我怀疑此警告是我的代码无法按预期执行的原因,有人可以尝试解释问题所在吗?
如果您尝试从 FILE*
读取数据,您需要使用 fscanf
,而不是 sscanf
。后者从字符串 (char *
).
另外,%d
需要传入一个对应的int指针,否则fscanf
不能修改整数
此外,您正在传递未初始化的 char*
s - fscanf
将尝试将您的字符串写入某个未定义的地址。您需要像 mnemonic
.
最后,无论何时使用 %s
,您都应该明确地告诉它缓冲区的大小。否则很容易溢出。
char R1[6];
char R2[6];
int immediate;
char mnemonic[6];
FILE *input = fopen("file.txt","r");
...
if (fscanf(input,
"%6s %6s %6s %d", mnemonic, R1, R2, &immediate) != 4) {
// bad things happened