跳转到内容

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;
}
华夏公益教科书