-
必须引用的包
#include <cstring> #include <stdio.h>
-
介绍
char a[40000];
gets(a);
gets从标准输入设备读字符串函数,其可以无限读取,不会判断上限,以回车结束读取,所以应该确保buffer的空间足够大,以便在执行读操作时不发生溢出;
a必须是char型数组,即char a[40000];这个40000代表的就是buffer
gets遇到空格不会停止输入,只有遇到换行符才会停止输入;
不管输入多少个空格,gets都会如实记录控制台输入的数据;
strlen()记录a数组实际的字符个数; -
基本方法
#include <iostream> #include <cstring>//必须是cstring,否则strlen()方法不能用 #include <stdio.h> using namespace std; int main() { char a[40000]; gets(a);//必须是char型数组,不能是其他类型数组 int len=strlen(a);//得到char型数组的实际长度 //执行其余操作 return 0; }
-
getchar();
getchar有一个int型的返回值。当程序调用getchar时,程序就等着用户按键。用户输入的字符被存放在键盘缓冲区中,直到用户按回车为止(回车字符也放在缓冲区中)。当用户键入回车之后,getchar才开始从stdio流中每次读入一个字符。getchar函数的返回值是用户输入的字符的ASCII码,若文件结尾(End-Of-File)则返回-1(EOF),且将用户输入的字符回显到屏幕。如用户在按回车之前输入了不止一个字符,其他字符会保留在键盘缓存区中,等待后续getchar调用读取。也就是说,后续的getchar调用不会等待用户按键,而直接读取缓冲区中的字符,直到缓冲区中的字符读完后,才等待用户按键。#include <stdio.h>//必须引用该包 getchar();
一般用于遇到回车(或换行)停止输入的判断;
#include <stdio.h> while((getchar())!='\n'){ }
c++中gets用法总结
最新推荐文章于 2025-02-26 11:31:07 发布