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

时间:2017-01-29 04:31:16

标签: c++ visual-c++ while-loop

我想制作一个基本的游戏类似的控制台程序...所以问题是,如果用户输入是N / n没有任何错误,我怎么能再次运行相同的功能....这是我的代码。当我输入N / n时,它变为picture ...我正在使用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;
}

1 个答案:

答案 0 :(得分:2)

不要使用全局变量!将它们作为参数传递或返回值。 using namespace std;是不好的做法。更好地使用完全限定名称。

您看到的问题是因为当您预先执行cin >> something;时,在getline(std::cin, name);时,Enter键的'\ n'仍然存在。然后你马上得到一个空名。

cin.clear()不符合您的想法,请参阅documentation

为防止这种情况发生,您可以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");