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

时间:2015-09-30 10:51:02

标签: c tabs space capture scanf

例如以下文字(在文件中):

18 [tab] Robert [tab]很高兴见到你

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

我用fscanf(文件,“%s \ t”,缓冲区)试了一下 但它捕获了以空格分隔的单词

由于

2 个答案:

答案 0 :(得分:1)

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

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

请记住检查返回值。

答案 1 :(得分:0)

根据您的示例,您可能还想跳过换行符和其他特殊控制字符。您可以使用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);
     */
}