gpt4 book ai didi

c - 当您不知道有多少个整数时,如何从 char 字符串中读取整数? (在 C 中)

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

#include <stdio.h>
#include <string.h>

static const char nameOfFile[] = "blablabla.txt";
char lineG [128];

static char * readLine()
{
static FILE *file;
if(file == NULL)
file = fopen ( nameOfFile, "r" ); //opens the file

if ( file != NULL )
{
if( fgets ( lineG, sizeof (lineG), file ) != NULL ) //reads a line from file
return lineG;
else
fclose ( file );
}

else perror ( nameOfFile );
return NULL;
}

int main (void)
{
char *line, a;
line=readLine();
char c;
int a[30],b[30];

sscanf(line,"%c %d%d%d%d",&c,a[0],b[0],a[1],b[1]);

return 0;
}

如您所见,我正在尝试从文件中读取 int 字符串。但我不知道会有多少 int couples (like 12,23;)。我正在寻找适合所有人的解决方案。
txt 文件将是这样的(两行或更多行)

A 12,54;34,65;54,56;98,90   B 23,87;56,98

最佳答案

使用%n 格式说明符并一次读取一个整数。的相关参数%n 填充了 sscanf() 读取到的字符串的索引。 C99 标准中格式说明符 n 的说明:

No input is consumed. The corresponding argument shall be a pointer to signed integer into which is to be written the number of characters read from the input stream so far by this call to the fscanf function. Execution of a %n directive does not increment the assignment count returned at the completion of execution of the fscanf function. No argument is converted, but one is consumed. If the conversion specification includes an assignment suppressing character or a field width, the behavior is undefined.

需要一个动态分配的数组(使用 malloc())来存储 int 并进行扩展(使用 realloc()) ) 按要求。读取 int 的简单示例(但不添加到数组):

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

int main()
{
const char* in = "15 16 17 18";
int i;
int pos = 0;
int total_pos = 0;

while (1 == sscanf(in + total_pos, "%d%n", &i, &pos))
{
total_pos += pos;
printf("i=%d\n", i);
}

return 0;
}

查看在线演示 @ http://ideone.com/sWcgw0 .

关于c - 当您不知道有多少个整数时,如何从 char 字符串中读取整数? (在 C 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636140/

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