函数中的 gets() 在第二次使用后被跳过
gets() in function gets skipped after second use
我正在尝试制作一个文本输入函数,如下所示InputText
函数:
char* InputText(char Dummy[256])
{
gets(Dummy);
return Dummy;
}
但是当再次调用该函数时,gets(Dummy)
被跳过。我已经通过StackOverflow(通过使用cin.ignore()
或cin.clear()
)研究了这个问题,但我似乎找不到正确的答案和解释。
这是我对该函数的程序:
#define pr_ cout<<
#define in_ cin>>
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
char* InputText(char Dummy[256]);
main()
{
char Quest;
do
{
char InputChar[256];
int InputLength;
pr_ "n Input text (Note: press Enter twice to finish input.)n >";
InputText(InputChar);
InputLength=strlen(InputChar);
pr_ "n You inputted : "<<InputChar;
pr_ "n String length: "<<InputLength;
do
{
pr_ "nn Restart program?n >";
in_ Quest;
if(Quest!='y' && Quest!='Y' && Quest!='n' && Quest!='N')
pr_ " System error: not an answer.";
}
while(Quest!='y' && Quest!='Y' && Quest!='n' && Quest!='N');
}
while(Quest=='y' || Quest=='Y');
}
char* InputText(char Dummy[256])
{
gets(Dummy);
return Dummy;
}
这是程序输出的示例,以及我提到的问题:
Input text (Note: press Enter twice to finish input.)
>I am Groot!
You inputted : I am Groot!
String length: 11
Restart program?
>y
Input text (Note: press Enter twice to finish input.)
>
You inputted :
String length: 0
Restart program?
>
所以我的问题:如何使gets()
部分不被跳过?对不起,如果我再次问这个问题。
更新1:从R Sahu的回答来看,我现在正在使用fgets()
。但它仍然被跳过了。
使用
do
{
pr_ "nn Restart program?n >";
in_ Quest;
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
if(Quest!='y' && Quest!='Y' && Quest!='n' && Quest!='N')
pr_ " System error: not an answer.";
}
为我工作。
告诫:
请不要使用gets
。它是安全问题的根源。请改用fgets
。请参阅为什么 get 函数如此危险以至于不应使用它?。
相关文章:
- 如何从给定字符串中删除第二次和第三次出现的$
- getopt_long_only第二次调用时返回 -1
- 读取文件在第二次调用时返回INVALID_HANDLE
- C++:std::ofstream 方法 open() 在第二次迭代时擦除打开的 ifstream 文件
- 解释为什么第二次分配会改变性能
- 当再次触发信号时,从Qt插槽执行的功能被第二次调用时会发生什么?
- 如何防止GUI挂起,同时允许第二次操作与Qt中的第一次操作一起执行
- 如何找到数组中值倒数第二次出现的索引
- arm_data在第二次运行我的程序时中止失败,然后
- Java 套接字读取在第二次读取时返回奇怪字符
- 提升 Asio SSL 无法第二次接收数据(第一次确定)
- CUDA 内核在第二次运行时运行得更快 - 为什么?
- 第二次调用 PyObject_CallObject() 失败
- 第二次运行C++时无法编译
- 第二次创建命令缓冲器时,在VKCMDDrawIndex中进行了segfault
- 我的C 程序第二次运行时首先编写文件内容
- SQLite3 第二次无法正常工作
- 第二次呼叫SDL_BlitSurface时出现故障
- C++ - 第二次二叉搜索的分段错误
- 函数中的 gets() 在第二次使用后被跳过