本文共 1944 字,大约阅读时间需要 6 分钟。
scanf读取字符
Let suppose, we want to read time in HH:MM:SS format and store in the variables hours, minutes and seconds, in that case we need to skip columns (:) from the input values.
假设,我们要读取HH:MM:SS格式的时间 ,并将其存储在小时 , 分钟和秒的变量中,在这种情况下,我们需要从输入值中跳过列(:)。
There are two ways to skip characters:
有两种跳过字符的方法:
Skip any character using %*c in scanf
在scanf中使用%* c跳过任何字符
And, by specifying the characters to be skipped
并且,通过指定要跳过的字符
%*c skips a character from the input. For example, We used %d%*c%d and the Input is 10:20 – : will be skipped, it will also skip any character.
%* c跳过输入中的字符。 例如,我们使用%d%* c%d ,并且Input is 10:20 – :将被跳过,也将跳过任何字符。
Example:
例:
Input Enter time in HH:MM:SS format 12:12:10 Output: Time is: hours 12, minutes 12 and seconds 10
Program:
程序:
#includeint main () { int hh, mm, ss; //input time printf("Enter time in HH:MM:SS format: "); scanf("%d%*c%d%*c%d", &hh, &mm, &ss) ; //print printf("Time is: hours %d, minutes %d and seconds %d\n" ,hh, mm, ss) ; return 0;}
Output
输出量
Enter time in HH:MM:SS format: 12:12:10Time is: hours 12, minutes 12 and seconds 10
We can specify the character that are going to be used in the input, for example input is 12:12:10 then the character : can be specified within the scanf() like, %d:%d:%d.
我们可以指定将在输入中使用的字符,例如,输入为12:12:10,则可以在scanf()中指定字符:,如%d:%d:%d 。
Example:
例:
Input Enter time in HH:MM:SS format 12:12:10 Output: Time is: hours 12, minutes 12 and seconds 10
Program:
程序:
#includeint main () { int hh, mm, ss; //input time printf("Enter time in HH:MM:SS format: "); scanf("%d:%d:%d", &hh, &mm, &ss) ; //print printf("Time is: hours %d, minutes %d and seconds %d\n" ,hh, mm, ss) ; return 0;}
Output
输出量
Enter time in HH:MM:SS format: 12:12:10Time is: hours 12, minutes 12 and seconds 10
翻译自:
scanf读取字符
转载地址:http://pfazd.baihongyu.com/