如何让程序在打印出 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

本文关键字:请求 语句 输入 course 字符串 if 程序 打印 while      更新时间:2023-10-16

如何在不切换程序中提问的顺序的情况下做到这一点?在询问课程之前,我想了解他们的年龄。但是,一旦键入年龄,程序就会自动继续打印 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;
}