简体   繁体   English

fscanf C编程错误

[英]fscanf c programming wierd error

I am not new to programming, but I encountered this small problem and I can't seem to get it. 我对编程并不陌生,但是遇到了这个小问题,似乎无法理解。 I want to read a file with dates and put them in another file with another format 我想读取一个带有日期的文件,然后将它们放在另一个具有另一种格式的文件中

Input example : 18.08.2015 输入示例 :18.08.2015
Output example : 18-08-2015 输出示例 :18-08-2015

Here is the code (dat1 has "r" permission and dat2 "w"): 这是代码(dat1具有“ r”权限,dat2具有“ w”权限):

char d[3];
char m[3];
char g[5];
while(fscanf(dat1,"%s.%s.%s\n",&d,&m,&g)==3)
{
    fprintf(dat2,"%s-%s-%s\n",d,m,g);
}

On the other hand, this works fine if I use [space] instead of a [dot] in the input file. 另一方面,如果我在输入文件中使用[space]而不是[dot],则可以正常工作。 (18 08 2015) (2015年8月18日)

What am I missing? 我想念什么? The solution has to be as simple as possible and with using fscanf, not fgetc or fgets, to be explained to students that are just beginning to learn C. Thanks. 解决方案必须尽可能简单,并且使用fscanf而非fgetc或fgets进行解释,以向刚开始学习C的学生解释。谢谢。

The %s pattern matches a sequence of non-white-space characters, so the first %s will gobble up the entire string. %s模式与一系列非空格字符匹配,因此前一个%s将吞噬整个字符串。

Why use char arrays at all, why not int? 为什么要使用char数组,为什么不使用int?

int d;
int m;
int g;
while(fscanf(dat1,"%d.%d.%d\n",&d,&m,&g)==3)
{
    fprintf(dat2,"%d-%d-%d\n",d,m,g);
}

The %d in fprintf will not output leading zeros though. 但是fprintf中的%d将不会输出前导零。 You'll have to teach your students a little bit extra or leave it for extra credit. 您将不得不额外教您的学生,或者留下额外的学分。

Since the scanf format %s reads up to the next whitespace character, it cannot be used for a string ending with a . 由于scanf格式%s读取下一个空格字符,因此不能将其用于以结尾的字符串 . Instead use a character class: %2[0-9] or %2[^.] . 而是使用字符类: %2[0-9]%2[^.] (Change the 2 to the maximum number of characters you can handle, and don't forget that the [ format code does not skip whitespace, so if you want to do that, put a space before the format code.) (将2更改为您可以处理的最大字符数,并且不要忘记[格式代码不会跳过空格,因此,如果要这样做,请在格式代码前加一个空格。)

Change 更改

  fscanf(dat1,"%s.%s.%s\n",&d,&m,&g)

to

  fscanf(dat1,"%[^.].%[^.].%[^.]\n",d,m,g);

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

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