现在的位置: 首页 > 综合 > 正文

Input_Output

2017年12月04日 ⁄ 综合 ⁄ 共 1983字 ⁄ 字号 评论关闭

NOTE 1: scanf输入字符串的时候与getchar不同,其他情况相同。


NOTE 2: scanf连续输入问题,scanf同getchar一样不会自动刷新缓冲区,读入多个参数时,不造成不匹配:

scanf considerations


Consider the following code;

     scanf("%d", &n);
     scanf"%c", &op);

Many students have done this, only to find the program "just skips through" the second scanf.

Assume you type 45\n in response to the first scanf. The 45 is copied into variable n. When your program encounters the next scanf, the remaining \n is quickly copied into the variable op.

One foolproof approach is to always flush the buffer. This will clear any pesky \n characters.

     scanf("%d", &n);
     flushall();         /* kill any characters left in buffer */
     scanf("%c", &op);
     flushall();


I tend to use an alternative when fetching input from the keyboard. Get the entire string from the keyboard using the function gets and then sscanf into the variables. The gets function fetches
the string up to and including the \n character, but it throws away the \n character.

     char s1[80];
     ....
     gets(s1); /* get an entire string from the keyboard. */
     sscanf(s1, "%s", &d);
     gets(s1);
     sscanf(s1, "%s", &op);

One big advantage of this approach is that it greatly simplifies writing to a file. Note in the following, all code to write input data to a file is the same; fprintf(f1, "%s\n", s1); which lends
itself well to block copying.

     char s1[80];
     ....
     gets(s1); /* get an entire string from the keyboard. */
     fprintf(f1, "%s\n", s1);
     sscanf(s1, "%s", &d);

     gets(s1);
     fprintf(f1, "%s\n", s1);
     sscanf(s1, "%s", &op);
Well, the other way I'd like to introduce is like this.Use %s instead of using %c, cause %c will get the \n character, but %s just throw it away.But this time, you'd store it in a array or string not a character variable anymore.
     char s2[2];
     int n;
     ....
     scanf("%d", &n);
     scanf("%s", s2);
And also, you should use your operator like s2[0].


NOTE 3: scanf参数问题,当用户的输入小于scanf的参数时:

There's no way for a simple scanf to recognise the difference between a 1 parameter and 2 parameter user input.
If you only type in 1 number, it will simply stick around until you type another number or some junk.

CODE:

  1 #include<stdio.h>
  2 
  3 int main()
  4 {
  5     int i;
  6 
  7     while(scanf("%d", &i) != EOF)
  8         printf("%d", i);
  9     
 10     return 0;
 11 }   
~     

INPUT:       1 2 3 4 5
OUTPUT:  12345

好的做法是检查scanf得到的参数的个数:

  1 #include<stdio.h>
  2 
  3 int main()
  4 {
  5     int i;
  6 
  7     while(scanf("%d", &i) == 2)
  8         printf("%d", i);
  9 
 10     return 0;
 11 }

参数不对直接退出!!

【上篇】
【下篇】

抱歉!评论已关闭.