如何在获取用户输入时运行相同的功能
How to run same function when taking user inputs
我想制作一个类似游戏机的基本程序。。。所以问题是,当用户输入为N/N时,我如何使相同的函数再次运行而没有任何错误。。。。这是我的密码。当我输入N/N时,它变为如图所示。。。我正在使用Visual Studio C++2015。提前感谢
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <cstdio>
#include <string>
#include <iomanip>
using namespace std;
string name;
int age;
char prompt;
void biodata()
{
cin.clear();
cout << "Name : "; getline(cin, name);
cout << "Age : "; cin >> age;
}
void showBio()
{
cin.clear();
cout << "Thank you for providing your data...";
cout << "nPlease confirm your data...(Y/N)n" << endl;
//printing border
cout << setfill('-') << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << endl;
//printing student record
cout << setfill(' ') << setw(1) << "|" << setw(15) << left << "Name" << setw(1) << "|" << setw(15) << left << "Age" << setw(1) << "|" << endl;
//printing border
cout << setfill('-') << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << endl;
//printing student record
cout << setfill(' ') << setw(1) << "|" << setw(15) << left << name << setw(1) << "|" << setw(15) << left << age << setw(1) << "|" << endl;
//printing border
cout << setfill('-') << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << setw(15) << "-" << setw(1) << "+" << endl;
//printing student record
cin >> prompt;
}
int main()
{
cout << "Hi User, my name is Cheary. I'm your Computated Guidance (CG), nice to meet you..." << endl;
cout << "Please provide your data..." << endl;
biodata();
showBio();
if (prompt == 'Y' || 'y')
{
cout << "Thank you for giving cooperation...nWe will now proceed to the academy..." << endl;
}
while (prompt == 'N' || 'n')
{
cout << "Please re-enter your biodata..." << endl;
biodata();
showBio();
}
system("pause");
return 0;
}
不要使用全局变量!将它们作为参数或返回值传递。using namespace std;
是不好的做法。最好使用完全限定名称。
您看到的问题是,当您上次执行cin >> something;
时,当涉及到getline(std::cin, name);
时,Enter键的'\n'仍然存在。然后你马上得到一个空名字。
cin.clear()
不会执行您认为的操作,请参阅文档。
为了防止这种情况,您可以使用std::ws
:
getline(cin >> std::ws, name);
这两个条件是错误的,而且总是正确的:
if (prompt == 'Y' || 'y') // equivalent to (prompt == 'Y' || 'y' not null)
while (prompt == 'N' || 'n') // same with 'n' not null
你必须写两次prompt
:
if (prompt == 'Y' || prompt == 'y')
while (prompt == 'N' || prompt == 'n')
使用std::cin.ignore(),而不是不可移植的std::system("pause");
。
相关文章:
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 更改运行时优先级队列的排序功能
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 为什么以下 POP 功能无法在主机或设备 (CUDA) 上运行?
- 零运行时成本功能标志
- 如何使用 Turbo C++并行运行两个功能,一个用于键盘,一个用于鼠标?
- 运行功能并保持循环运行C
- 如何使功能"run"工作。程序在调用运行时退出
- 如何子类可运行任何成员功能
- C++ OPEN SSL 库 HMAC 功能返回值每次运行时都不相同
- 在已经运行的功能C 中更改变量
- 从成员变量更新类变量或调用类功能是给出运行时错误
- 如何使特定的部分功能运行并返回主循环
- 运行简单的C 功能
- CIN验证功能有时不会自动运行
- Qthread中的运行功能 - 应用程序将悬挂
- 显示对话框后运行功能
- C 从控制台运行功能
- 运行功能时会遇到错误
- 关闭控制台时C++/Qt运行功能