2016-04-25 1 views
0

私のプログラムの質問の順序を入れ替えることなく、コースを尋ねる前に、自分の年齢を取得したいと思います。しかし、年齢が設定されると、プログラムは自動的にwhile/ifステートメントを印刷します。while/if文を出力する前に、文字列 "course"の入力をプログラムに要求するにはどうすればいいですか?

#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; 
} 
+0

コースの質問を 'if(1 hauron

答えて

0
#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); 
    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 !\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; 
} 
1

getline()cin >>後に使用されている場合は、getline()は先頭の空白としてこの改行文字を見て、それはただのさらに読んで停止します。

ソリューション:

  • コールcin.ignore()cin>>
から改行文字を消費するためにダミーのコール getline()を行い getline()

それとも

  • を呼び出す前に
関連する問題