C++ gets() 函数
gets() 函数原型
char* gets(char* str);
gets()
函数从 stdin 读取字符,并将它们存储在 str
中,直到遇到换行符或文件结束符。
gets()
与 fgets() 的区别在于,gets()
使用的是 stdin
流。gets()
函数没有提供防止缓冲区溢出的支持,如果提供了大型输入字符串,可能会发生缓冲区溢出。
它定义在 <cstdio>
头文件中。
注意: 避免使用 gets()
函数,因为它可能对程序造成危险。该函数在 C++11 中被弃用,并在 C++14 中被移除。
gets() 参数
str
:指向字符数组的指针,用于存储来自 stdin 的字符。
gets() 返回值
- 成功时,
gets()
函数返回str
- 失败时,返回
NULL
。 - 如果失败是由文件结束条件引起的,它会在
stdin
上设置 eof 指示符。 - 如果失败是由其他错误引起的,它会在
stdin
上设置错误指示符。
示例:gets() 函数的工作方式
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
char str[100];
cout << "Enter a string: ";
gets(str);
cout << "You entered: " << str;
return 0;
}
当你运行程序时,可能的输出将是:
Enter a string: Have a great day!
You entered: Have a great day!