跳轉到內容

C++ 程式設計/練習/標準 IO

來自華夏公益教科書,開放的書籍,面向開放的世界

初學者練習:標準 IO 流

[編輯 | 編輯原始碼]

以下挑戰將幫助你鞏固你所學到的知識,併為你開始實驗提供一個起點

編寫一個簡單的程式,當執行時,它會詢問使用者他們的姓名和年齡,然後將這些資訊顯示給使用者。示例輸入/輸出和可能的措辭在下面提供

Hello. What is your name?
Hello, <name>. How old are you?
<name> is <age> years old.
解決方案 #1
#include <iostream>

using namespace std;

int main(int argc, char** argv){

  // Get the name
  string name;

  cout<<"Hello. What is your name? "<<endl;
  cin>>name;

  // Get the age
  int age;

  cout<<"Hello, "<<name<<". How old are you? "<<endl;
  cin>>age;

  // Show the name and age
  cout<<name<<" is "<<age<<" years old."<<endl;

  return;
}
解決方案 #2
//by blazzer12
// Program which asks the user for their name and age, and then displays back.

#include<iostream>

using namespace std;

int main()
{
	string name;
	int age;
	
	//get name
	cout<<"Hello! What is your name?"<<endl;
	cin>>name;
	
	//get age
	cout<<"How old are you, "<<name<<" ?"<<endl;
	cin>>age;
	
	//print name and age
	cout<<"So, "<<name<<", you are age is "<<age<<endl;
}
華夏公益教科書