gpt4 book ai didi

c - 根据空格分隔符读取文件

转载 作者:行者123 更新时间:2023-11-30 17:56:32 25 4
gpt4 key购买 nike

我有包含 4 行数据的文本文件。每行如下

Candies 2
Cookies -4
Soda 5
Milk 8

我必须读取 C 函数中的值 (2,-4,5,8) 并将它们存储在变量中。

我已经编写了以下代码,但我卡在了 XXXXXX 所指示的位置。我不确定那里和之后到底发生了什么。感谢您的帮助。

  void function()
{
int count=0,value[4],length=0;

FILE *fp;

fp = fopen("file.txt","r");

if (fp == NULL)
{
fprintf(stderr, "Can't open file !\n");
exit(1);
}

char line[100];
for (count = 0; count < 4; count++)
{
if (fgets(line,sizeof(line),fp)==NULL)
break;

else
{

while(fp!="" && length<strlen(line))
{
fp++;length++
}

if(fp == "")
value[count]= XXXXXXXX;
}
}

最佳答案

不要增加fp。它不会做你认为它会做的事。

如果您想在现有 C 函数的帮助下做到这一点,只需在您的行中搜索空格即可(好吧,我在这里使用了 isspaceatoi):

int pos = 0;
while( line[pos] != 0 && !isspace(line[pos]) ) pos++;
if( line[pos] != 0 ) {
line[pos++] = 0;
value[count] = atoi( &line[pos] );
printf( "Key: '%s' / Value: %d\n", line, value[count] );
}

或者您可以使用sscanf...

int nread = sscanf( line, "%*s %d", &value[count] );

或者:

char key[100];
int nread = sscanf( line, "%s %d", key, &value[count] );

关于c - 根据空格分隔符读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13447088/

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