gpt4 book ai didi

c - 为什么不打印连字符 (-)?

转载 作者:太空宇宙 更新时间:2023-11-04 06:54:39 25 4
gpt4 key购买 nike

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char* argv[])
{
FILE* fp = fopen(argv[1],"r");
char* ptr;
int size;
while(1){
int scanfinteger = fscanf(fp,"%d",&size);
ptr = (char*)malloc((size+1)*sizeof(char));
if(scanfinteger != 1){
int result = fscanf(fp,"%s",ptr);

printf("ptr:[%s]\n",ptr);
if(result == EOF)
break;
}
}
return 0;

}

input_file(argv[1]) 包含这个

10 This
10 is
10 buffers
10 -
10 hi
10 -hello

我的程序的输出

ptr: [This]
ptr: [is]
ptr: [buffers]
ptr: [10]
ptr: [hi]
ptr: [hello]

我不明白为什么连字符会被消耗掉。有人见过这个问题吗?谢谢!

最佳答案

如果我可以建议不同的解决方案,我建议您阅读,然后解析这些行。

也许是这样的:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char* argv[])
{
// First make sure you have enough arguments
if (argc < 2)
{
printf("Need an argument!\n");
return 1;
}

// Open the file, and make sure we succeeded
FILE *fp = fopen(argv[1], "r");
if (fp == NULL)
{
printf("Failed to open the file %s: %s\n", argv[1], strerror(errno));
return 1;
}

// Now read the file, one line at a time
char line[100];
while (fgets(line, sizeof line, fp) != NULL)
{
// Now we have a line, attempt to parse it
int value;
char string[100];
if (sscanf(line, "%d %99s", &value, string) != 2)
{
printf("Failed to parse the current line\n");
break; // Break out of the loop
}

printf("Read value %d, string '%s'\n", value, string);
}

// All done, or we had an error (should probably check that)
// Anyway, close the file and end the program
fclose(fp);
}

您当前代码的问题(这似乎不是您运行的实际代码)是您仅在读取数字失败时才读取字符串。

我不知道产生该输出的实际代码有什么问题。但不知何故,它不同步。这可以看出,您将一行中的数字作为字符串读取。

关于c - 为什么不打印连字符 (-)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46661699/

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