本文介绍了C-sscanf不忽略空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个文本文件,并使用逗号作为定界符,但下面的行确实有效,但是当我打印出lname时,它不会忽略逗号后的空白并在名称前打印一个空格.如何调整代码以忽略空白?

I am reading in a text file and using a comma as a delimiter, the line below does work however when I print out lname it does not ignore the white space after the comma and prints a space before name. How can I adjust the code to ignore white space?

文字示例:

Rob,Smith,4、12,一些文字
史蒂夫·琼斯(Steve,Jones),41岁,286岁,

Rob, Smith, 4, 12, sometext
Steve, Jones, 41, 286, sometext

sscanf(line, "%[^,],%[^,],%d,%d,%s", fname,lname,&num1,&num2,info);

推荐答案

如果要忽略空格,只需添加一个空格字符:

Just add a whitespace character if you want to ignore whitespace:

sscanf(line, " %[^,], %[^,], %d, %d, %s", fname, lname, &num1, &num2, info);

%d%s之前的空格不是必需的,因为它们已经跳过了前导空格字符.不会跳过前导空白的唯一格式说明符是%c%[%n.

The space before %d and %s are not required as they already skip leading whitespace characters. The only format specifiers which does not skip leading whitespace are %c, %[ and %n.

请注意,*scanf格式字符串中的空白字符会指示scanf扫描任意数量的空白,包括无空白,直到第一个非空白字符为止.

Note that a whitespace character in the format string of *scanf instructs scanf to scan any number of whitespace, including none, until the first non-whitespace character.

这篇关于C-sscanf不忽略空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 13:15