繁体   English   中英

如何使用fscanf在C中捕获由制表符分隔的文件中的字符串

[英]How can I capture with fscanf, in C, strings from a file separated by tabulators

例如,以下文本(在文件中):

18 [tab] Robert [tab]很高兴再次见到您

我希望捕获我的代码:-18-罗伯特-再次见到你很高兴

我用fscanf(file,“%s \\ t”,buffer)尝试过,但是它捕获了用空格分隔的单词

谢谢

使用字符集,即fscanf(file, "%[^\\t]\\t", buffer);

^表示“除以下字符外的所有字符”。

请记住检查返回值。

根据您的示例,您可能还希望跳过换行符和其他特殊控制字符。 您可以使用scanf字符串转换%[来包含所需字符或排除不需要的字符,例如:

/* exclude only '\t' and '\n' */
fscanf(file, "%[^\t\n]", buffer);
/* include only alphanumeric characters and space */
fscanf(file, "%[0-9A-Za-z ]", buffer);
/* include all ASCII printable characters */
fscanf(file, "%[ -~]", buffer);

您还应该确保buffer有足够的空间。 如果您无法控制提供的输入字符串长度,则可以使用十进制整数限制最大字段宽度。 在开始解析下一个合适的字符串之前,可以跳过所有不需要的符号。 可以使用相反的转换模式和分配抑制修饰符%*

char buffer[101]; /* +1 byte for terminating '\0' */

/* Scan loop */
{
    /* Skip all non printable control characters */
    fscanf(file, "%*[^ -~]");

    /* Read up to 100 printable characters so the buffer cannot
     * overflow. It is possible to run the following line in a loop
     * to handle case when one string does not fit into single buffer
     * checking function return value, since it will return 1
     * if at least one wanted character is found */
    fscanf(file, "%100[ -~]", buffer);

    /*
     * If scan would be performed only by the following line it is possible
     * that nothing could be read if the first character is not matching
     * fscanf(file, "%100[ -~]%*[^ -~]", buffer);
     */
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM