如何让程序在打印出 while/if 语句之前请求输入字符串"course"
How do I get the program to request for input for the string "course" before they print out the while/if statement
如何在不切换程序中提问的顺序的情况下做到这一点?在询问课程之前,我想了解他们的年龄。但是,一旦键入年龄,程序就会自动继续打印 while/if 语句。
#include<iostream>
#include<string>
using namespace std;
int main()
{
int age; //Declares the variable "age"
string name;
string course;
cout << "Hin"; //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 << "nnHow 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 !nn";
}
//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>>
中的尾随换行符
#include<iostream>
#include<string>
using namespace std;
int main()
{
int age; //Declares the variable "age"
string name;
string course;
cout << "Hin"; //Prints out "Hello World"
cout << "What is your name? ";
getline(cin, name);
while(true) {
cout << "nHow old are you ? "; //Ask the user their age
cin >> age; //Records the value entered by user
if(age>=0)
break;
cout << "nYou can't be younger than 0 years old.nPlease try again.";
}
cout << "What course are you picking up in university ? ";
getline(cin, course);
//If number entered is larger than 100, print the following message
if (age > 100) {
cout << "nYou are such a blessed person !nn";
}
//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;
}
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 我的简单if-else语句是如何无法访问的代码
- 有一个打印语句的函数是一种糟糕的编程实践吗
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 为什么是0;C++中的有效语句
- 如何在boost beast http请求中设置http头
- 发送一个带有libcurl C++问题的帖子请求:s
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 在多个核心中处理一个HTTP请求
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 我似乎对if/else的基本语句有问题:/
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- C++ if 语句未按预期工作,在请求输入之前打印"else"
- 如何让程序在打印出 while/if 语句之前请求输入字符串"course"