gpt4 book ai didi

c++ - 如何在接受用户输入时运行相同的功能

转载 作者:行者123 更新时间:2023-11-28 01:53:47 25 4
gpt4 key购买 nike

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

最佳答案

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

你看到的问题是因为当你之前执行cin >> something;时,当涉及到getline(std::cin , 姓名);。然后您会立即得到一个空名称。

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");

关于c++ - 如何在接受用户输入时运行相同的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41917604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com