简体   繁体   English

如何使用fscanf将任何字符读入字符串,直到到达选项卡?

[英]How to use fscanf to reads any character into a string until a tab is reached?

How to use fscanf to reads any character into a string until a tab is reached? 如何使用fscanf将任何字符读入字符串,直到到达选项卡?

My data file have only 1 row: 我的数据文件只有一行:

123'\t'(Tab)345'\t'Le Duc Huy'\t'567

and i use fscanf like this: 我使用像这样的fscanf:

fscanf(fin,"%d %d %d %[^\t]%s %d",&m,&n,&k,s,&q);

it return q with wrong value. 它以错误的值返回q。 Anybody can tell me what made it failed? 谁能告诉我是什么让它失败了?

Using fscanf() , you will need a negated character class and a length: 使用fscanf() ,您将需要一个否定的字符类和长度:

char string[32];

if (fscanf(fp, "%31[^\t]", string) != 1)
    ...error or EOF...

The modified version of the question has a data string with a single quote after the final tab, and the single quote cannot be converted to an integer, so the value in q is undefined. 问题的修改版本在最终选项卡后面有一个带有单引号的数据字符串,并且单引号无法转换为整数,因此q的值未定义。 Note that you must check the return value of fscanf() to ensure that all the fields you expected to match actually did match, In the context, if probably returned the value 4 instead of 5, telling you there was an error. 请注意,您必须检查fscanf()的返回值,以确保您希望匹配的所有字段实际匹配,在上下文中,如果可能返回值4而不是5,则告诉您出现错误。

Instead of fscanf I would just use fgetc (though my syntax may be off a bit): 而不是fscanf我会使用fgetc (虽然我的语法可能有点偏差):

int c;
string s = "";
for (;;)
{
    c = fgetc(somefile);
    if (c == '\t' || c == EOF) break;
    s += c;
    // ...
}

这是fscanf()版本:

fscanf (stream, "[^\t]", output);

Note, this is not safe! 注意,这不安全!


char foo[100];
scanf("%s\t", foo);

You have no way of keeping the user from overflowing the buffer 您无法阻止用户溢出缓冲区

Eliminate the space before %[ . 消除%[之前的空间。 It's eating your tab. 它在吃你的标签。 Also, as others have said, this code is unsafe and probably unreliable on input that's not formatted exactly as you expect. 此外,正如其他人所说,这段代码是不安全的,并且可能在输入上不可靠,而且输入的格式与预期不完全相同。 It would be better to use fgets and then parse it yourself with strtol and a few for loops. 最好使用fgets ,然后使用strtol和一些for循环自己解析它。

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

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