gpt4 book ai didi

C 使用 scanf() 进行 |分隔字符串

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

我想输入一些字符串,然后输入两个整数。字符串由“|”分隔,而整数则由“.”分隔。

在网上查找时,我看到了某种涉及 [^] 的语法。我正在使用这个,但它根本不起作用。有人可以指出我应该做什么以及为什么我所做的事情是错误的吗?

sscanf(str, "%s[^|],%s[^|],%s[^|],%i[^|],%i[^.]", …);

最佳答案

语法充其量是晦涩难懂的 - 我建议使用不同的方法,例如 strtok() ,或使用字符串处理函数进行解析 strchr()等等

但是,您必须意识到的第一件事是 %[^<delimiter-list>]格式说明符(行话中的“扫描集”,由 POSIX scanf() 记录)在许多其他地方)仅提取字符串字段 - 如果提取的字符串代表的是整数,则必须将其转换为整数。

其次,您仍然必须在格式说明符之外包含分隔符作为文字匹配字符 - 您已使用逗号分隔格式说明符,其中 |在输入流中。

考虑以下因素:

#include <stdio.h>

int main()
{
char a[32] ;
char b[32] ;
char c[32] ;
char istr[32] ; // Buffer for string representation of i
int i ;
int j ; // j can be converted directly as it is at the end.

// Example string
char str[] = "fieldA|fieldB|fieldC|15.27" ;

int converted = sscanf( str, "%[^|]|%[^|]|%[^|]|%[^.].%i", a, b, c, istr, &j ) ;

// Check istr[] has a field before converting
if( converted == 5 )
{
sscanf( istr, "%i", &i) ;
printf( "%s, %s %s, %d, %d\n", a, b, c, i, j ) ;
}
else
{
printf( "Fail - %d fields converted\n", converted ) ;
}

return 0 ;
}

关于C 使用 scanf() 进行 |分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34115228/

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