1.getchar()
- 说明
- 语法
int getchar(void);
- 参数
(none);
- 头文件
stdio.h (C) or cstdio (C++);
- 返回值
函数返回读取的字符,将读取的字符按unsigned char 类型强制转换为int类型,及返回字符的ASCII码;
返回“EOF”表示读取到文件结尾或者读取错误。
返回“EOF”表示读取到文件结尾或者读取错误。
<--查看具体解释,链接:http://www.cplusplus.com/reference/cstdio/getchar/-->
<--附上测试代码,错误检测代码,链接:http://en.cppreference.com/w/c/io/getchar-->
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int ch;
while ((ch=getchar()) != EOF) /* read/print "abcde" from stdin */
printf("%c", ch);
/* Test reason for reaching EOF. */
if (feof(stdin)) /* if failure caused by end-of-file condition */
puts("End of file reached");
else if (ferror(stdin)) /* if failure caused by some other error */
{
perror("getchar()");
fprintf(stderr,"getchar() failed in file %s at line # %d\n", __FILE__,__LINE__-9);
exit(EXIT_FAILURE);
}
return EXIT_SUCCESS;
}
Output:
正常输入字符,输入以回车结尾,然后打印输入的内容。
输入特殊字符,Windows平台为(Ctrl+Z),
输出:End of file reached
输入特殊字符,Windows平台为(Ctrl+Z),
输出:End of file reached
- 例程
<--MSDN例程,链接:https://msdn.microsoft.com/zh-cn/library/x198c66c.aspx-->
// crt_getchar.c
// Use getchar to read a line from stdin.
#include <stdio.h>
int main()
{
char buffer[81];
int i, ch;
for (i = 0; (i < 80) && ((ch = getchar()) != EOF)
&& (ch != '\n'); i++)
{
buffer[i] = (char) ch;
}
// Terminate string with a null character
buffer[i] = '\0';
printf( "Input was: %s\n", buffer);
}
Output:
Input was:******
2.getch()
- 说明
- 语法
int getch(void);
- 参数
(none);
- 头文件
<conio.h>
- 返回值
返回字符从键盘输入字符的ASCII码。
- 例程
#include"conio.h"
void main()
{
char ch;
ch = getch();
printf("Input Char Is :%c",ch);
}
Output:
Input Char Is : *
3.scanf()
<--参考MSDN解释,链接:https://msdn.microsoft.com/zh-cn/library/9y6s16x1(v=vs.71).aspx-->
<--参考tutorialspoint解释,链接:https://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm-->
- 说明
从控制台读取格式化的数据。
- 语法
int scanf( const char *format [, argument]... );
- 参数
format Format control string.
argument Optional arguments.
argument Optional arguments.
- 头文件
<stdio.h>
- 返回值
返回成功转换和分配字段的数目,不包含已经读取但是没有转换的数目;如果返回值是0表示没有转换任何字段。
当出现错位,或者读取到文件结束符,或者第一次读取字符读取到字符串的结尾字符,返回EOF。
- 例程
// crt_scanf.c
/* This program uses the scanf and wscanf functions
* to read formatted input.
*/
#include <stdio.h>
int main( void )
{
int i, result;
float fp;
char c, s[81];
wchar_t wc, ws[81];
result = scanf( "%d %f %c %C %80s %80S", &i, &fp, &c, &wc, s, ws );
printf( "The number of fields input is %d\n", result );
printf( "The contents are: %d %f %c %C %s %S\n", i, fp, c, wc, s, ws);
result = wscanf( L"%d %f %hc %lc %80S %80ls", &i, &fp, &c, &wc, s, ws );
wprintf( L"The number of fields input is %d\n", result );
wprintf( L"The contents are: %d %f %C %c %hs %s\n", i, fp, c, wc, s, ws);
}
Input:
71 98.6 h z Byte characters 36 92.3 y n Wide charactersOutput:
The number of fields input is 6 The contents are: 71 98.599998 h z Byte characters The number of fields input is 6 The contents are: 36 92.300003 y n Wide characters
注:由于本人水平有限,如有理解或描述错误,还请各位批评指正。