下使用scanf()的供|分隔字符串 [英] C using scanf() for | delimited string
问题描述
我想输入几串然后两个整数。 |虽然字符串分隔,整数由保持分开。。
环顾四周网上我看到了某种语法涉及 [^]
。我使用这一点,但它是不工作的。可有人请指出我应该做的,为什么我在做什么是错的?
的sscanf(STR,%s的[^ |]%S [^ |]%S [^ |]%I [^ |]%I [^。 ],...);
的语法是神秘充其量 - 我会用不同的方法,如 strtok的建议()
,或字符串处理函数解析和strchr()
等
但是你必须明白的第一件事是,%[^<定界符列表>]
格式说明(一'的扫描设置中的术语,通过记录POSIX scanf()的
一>
其中包括许多其他地方)只提取字符串字段 - 你必须转换提取的字符串转换为整数,如果这是他们重新present。
其次,你还必须包含分隔符的格式说明外的字面匹配字符 - 你已经用逗号分隔的格式说明,其中 |
都是输入流中
考虑以下几点:
的#include<&stdio.h中GT;诠释的main()
{
所以char a [32];
焦B〔32〕;
焦C [32];
焦炭ISTR [32]; //缓冲区字符串再我的presentation
INT I;
诠释J; // J可以获得直接,因为它是在最后被转换。 //例串
烧焦海峡[] =FIELDA | fieldB | fieldC | 15.27; int转换= sscanf的(STR,%[^ |] |%[^ |] |%[^ |] |%[^]%I,A,B,C,ISTR,&放大器; j)条; //检查ISTR []有一个字段转换前
如果(转换== 5)
{
sscanf的(ISTR,%I,&安培; I)
的printf(%s和%s%S,%D,%d个\\ N,A,B,C,I,J);
}
其他
{
的printf(故障 - %d个领域转化\\ n,转换);
} 返回0;
}
I want to input a few strings then two integers. Whilst the strings are separated by '|', the integers are kept apart by a '.'.
Looking around online I have seen some sort of syntax which involves [^]
. I am using this but it is not working at all. Can someone please point out what I should be doing and why what I am doing is wrong?
sscanf(str, "%s[^|],%s[^|],%s[^|],%i[^|],%i[^.]", …);
The syntax is arcane at best — I'd suggest using a different approach such as strtok()
, or parsing with string handling functions strchr()
etc.
However the first thing you must realise is that the %[^<delimiter-list>]
format specifier (a 'scan set' in the jargon, documented by POSIX scanf()
amongst many other places) only extracts string fields — you have to convert the extracted strings to integer if that is what they represent.
Secondly you still have to include the delimiter as a literal match character outside of the format specifier — you have separated the format specifiers with commas where |
are in the input stream.
Consider the following:
#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 ;
}
这篇关于下使用scanf()的供|分隔字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!