gpt4 book ai didi

c++ - 如何让程序在打印出 while/if 语句之前请求输入字符串 "course"

转载 作者:行者123 更新时间:2023-11-28 05:42:30 24 4
gpt4 key购买 nike

如何在不切换程序中提问顺序的情况下做到这一点?在询问类(class)之前,我想了解他们的年龄。但是,一旦输入年龄,程序就会自动继续打印 while/if 语句。

#include<iostream>
#include<string>
using namespace std;

int main()
{

int age; //Declares the variable "age"
string name;
string course;


cout << "Hi\n"; //Prints out "Hello World"
cout << "What is your name? ";
getline(cin, name);
cout << "\nHow old are you ? "; //Ask the user their age
cin >> age; //Records the value entered by user
cout << "What course are you picking up in university ? ";
getline(cin, course);

//If number entered is smaller than 0, print the following message
while (age < 0 ) {
cout << "\nYou can't be younger than 0 years old.";
cout << "\nPlease try again";

cout << "\n\nHow old are you ? ";
cin >> age;
}

//If number entered is larger than 100, print the following message
if (age > 100) {
cout << "\nYou are such a blessed person !\n\n";
}

//If number entered is between 1 and 99, print the following message
if (age > 1 && age < 99) {
cout << "Your name is " << name << " ,and you are " << age << " years old.";
cout << "\n You are planning on taking " << course << " in university.";
}

return 0;
}

最佳答案

如果在 cin >> 之后使用 getline()getline() 会将这个换行符视为前导空格,它只是停止阅读。

解决方法:

  • 在调用 getline() 之前调用 cin.ignore()

或者

  • 进行虚拟调用 getline() 以使用 cin>> 中的尾随换行符

关于c++ - 如何让程序在打印出 while/if 语句之前请求输入字符串 "course",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36838049/

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