如何在获取用户输入时运行相同的功能

How to run same function when taking user inputs

本文关键字:运行 功能 输入 获取 用户      更新时间:2023-10-16

我想制作一个类似游戏机的基本程序。。。所以问题是,当用户输入为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");