gpt4 book ai didi

c - 连续使用 2 个 fscanf

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

我想从 C: 中的以下文件中读取

示例file.txt:

ab cd efg mnop

1234 123 12 21

我想读取空格分隔的单词并将其存储在各个变量中。我知道我可以使用:

fscanf(fp, "%s %s %s.....", var1, var2, varN);

但是,我的代码(对于大学)不需要这个 fscanf(fp, "%s %s %s.....", var1,var2,varN); .

我需要连续使用 fscanf 的代码片段(针对大学)是:

                   ......
while(!feof(fp)) {
fscanf(fp,"%2s",posRobot);

if(!strcmp(posRobot, "R1") == 0){
fscanf(fp, "%4s", pos_temp);
posR1_temp=0;
.......

但它没有按预期工作。我寻求帮助的代码:

int main()
{
FILE *fp;
char var1[2];
char var2[2];
char var2[3];
char var2[4];
....


fp = fopen("file.txt", "r");
if(fp == NULL) {
printf("Error opening file!");
exit(0);
}

//now using fscanf, trying to read the first two characters.
fscanf(fp,"%s",var1);

//test to see if i read it successfully
printf("\n1st 'fscanf' : %2s",var1);

//now using fscanf again, to read the next string.
fscanf(fp,"%s",var2);

//test to see if i read it successfully
printf("\n1st 'fscanf' : %2s",var2);

错误:编译成功,但输出窗口上没有显示任何内容。

最佳答案

非常感谢你们,非常快的答复。问题是我没有为“空字符”分配另一个“空间”

工作代码:

int main()
{
FILE *fp;
char xxx[3];
char bb[3];
char cc[4];
char aa[5];
char hh[4];

fp=fopen("fscanf.txt", "r");
if(fp==NULL){
printf("Error opening file!");
exit(0);
}


fscanf(fp,"%s",xxx);
printf("\n1st 'fscanf' : %3s",xxx);

fscanf(fp,"%s",bb);
printf("\n2nd 'fscanf' : %3s",bb);

fscanf(fp,"%s",cc);
printf("\n3rd 'fscanf' : %4s",cc);

fscanf(fp,"%s",aa);
printf("\n4th 'fscanf' : %5s",aa);

fscanf(fp,"%s",hh);
printf("\n5th 'fscanf' : %4s",cc);

return 0;

}

关于c - 连续使用 2 个 fscanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56529783/

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