gets() 不接受输入
gets() not taking input
我有一些大学工作,因为我注意到gets()不起作用,但我无法弄清楚为什么。
我尝试将 getch() 和 getchar() 放在 gets() 之前,但还有其他问题。
当我在do-while(标记为-----> 3)之前编写实现gets()的代码时,它可以工作!!
有人可以帮助我吗?
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
class student
{
int rollNo;
char department[20];
int year;
int semester;
public:
student()
{
rollNo=0;
year=0;
semester=0;
}
void getData();
void promote();
void changeDepartment();
void display();
};
void student::changeDepartment()
{
if(rollNo!=0)
{
cout<<"nEnter the new Departmentn";
gets(department); -------------->1
}
else
{
cout<<"nStudent not confirmedn";
}
}
void student::getData()
{
cout<<"nEnter the roll non";
cin>>rollNo;
cout<<"nEnter the yearn";
cin>>year;
cout<<"nEnter the semestern";
cin>>semester;
cout<<"nEnter the departmentn";
gets(department); ----------------> 2
}
void student::promote()
{
if(rollNo!=0)
{
semester+=1;
if(semester%2==1)
{
year+=1;
}
}
else
{
cout<<"nStudent not confirmedn";
}
}
void student::display()
{
if(rollNo!=0)
{
cout<<"nRoll No : "<<rollNo;
cout<<"nYear : "<<year;
cout<<"nSemester : "<<semester;
cout<<"nDepartment : "<<department;
}
else
{
cout<<"nStudent not confirmed";
}
}
int main()
{
student s;
int ch;
char choice;
----------------> 3
do
{
cout<<"nMain Menu";
cout<<"n1. Enter student details";
cout<<"n2. Change department of student ";
cout<<"n3. Promote student ";
cout<<"n4. Display student details ";
cout<<"nEnter your choice ";
cin>>ch;
switch(ch)
{
case 1 : s.getData();
s.display();
break;
case 2 : s.changeDepartment();
s.display();
break;
case 3 : s.promote();
s.display();
break;
case 4 : s.display();
break;
}
cout<<"nDo you want to continue? (Y/n)n";
cin>>choice;
}while((choice=='y')||(choice=='Y'));
return(0);
}
不要使用 get
使用cin.getline()
而不是gets
,无论您在哪里使用gets
。
cin.getline(department, sizeof department);
gets
已过时,因为无法指定输入大小,因此存在缓冲区溢出的危险。
摆脱不需要的换行符
在您的情况下,gets
使用了上一个输入中的(未丢弃的)换行符,因此存储了一个空字符 *。使用cin.ignore()
来摆脱不需要的空间 - 使用getline()
时也需要这个。
或者,你可能始终希望使用 cin.getline()
以一致的方式读取用户输入,然后根据预期的数据类型分析输入。这也将允许您执行更好的错误检查。
你混合了C和C++。当然,这是允许的,但有一种叫做使用语言的惯用方式;这意味着语言用户有一种自然的方式来以优雅的方式表达结构。我建议更改的两个地方:
- 使用
std::string
s 而不是char
数组;std::string department;
- 使用
std::getline(std::cin, department);
数组因是丰富的错误来源而臭名昭著。将这种低级内存管理留给可用的标准库工具。
相关文章:
- 为什么线程不接受此输入?
- B不接受8作为输入的是什么?C++
- C++数组输入不接受一定数量的整数
- 斯堪夫不接受输入
- C++字符数组不接受超过 4 个字符的输入
- CIN不接受C++中带有空格的输入?
- std::cin不接受输入
- 为什么我的代码在要求打印长度和宽度的值后不接受多个输入?
- 在此代码中,它不接受 i=0 的输入.它直接用于 i=1
- 有没有一种方法可以接受数字数组而不接受垃圾值的输入
- 扫描线C++不接受输入的功能
- 菜单选择器不接受有效输入
- SCANF 在 Eclipse 中不接受调试模式下的输入?
- #defined 函数只能接受原始输入而不接受变量?
- 我的C++程序不接受菜单后的输入
- 找出一个正方形逻辑中可能的网格数量,但代码不接受超过六个输入,它停止并说.exe停止工作
- C++控制台不接受键盘输入
- 程序不接受任何输入.第一次输入后,它会自动关闭
- 为什么getline不接受输入
- uint8_t不接受两位数的输入