我想制作一个基本的类似于游戏的控制台程序...所以,问题是,当用户输入为N / n时,如果没有任何错误,如何使同一功能再次运行....这是我的代码。当我输入N / n时,它将变成图片... Im使用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;
,回车键的'\ n'仍然存在getline(std::cin, name);
。然后,您立即得到一个空名称。
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");
不可移植的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句