2017-02-21 34 views
-1
/* 
* hello_world.cpp 
* 
* Created on: Feb 21, 2017 
*  Author: George Lutas 
*/ 

#include <iostream> 
#include <string> 
#include <vector> 
#include <algorithm> 
#include <cmath> 

using namespace std; 

inline void keep_window_open() { char ch; cin>>ch; } 

int main()  //C++ programs start by executing the function main 
{ 
    cout << "George 17\n"; 
    string first_name = "George"; 
    int age = 17; 
    cin >> first_name >> age; 
    cout << "Hello," << first_name << "(age" << age << ")" << endl; 
} 

这是我的代码。我在这里错过了什么。代码的目标是输出“你好,乔治(17岁)”。那么,我怎样才能读懂它,而不是“George 17”?另外,我知道我没有安装std_lib_facilities.h。这是有意的。我很确定(事实上没有错误出现),我有我需要加载的库。C++代码cout打印而不是等待它在字符串中使用

+0

''''cin'''没有附加到''''cout'''''。你基本上写出了“乔治17”终端,然后在键盘输入阻塞。 – mascoj

+0

@mascoj扩展:至少使用'<< std :: flush'来强制输出到终端。 –

+0

@πάνταῥεῖ - 不,不需要'std :: flush'。 'std :: cin'和'std :: cout'是绑定的,因此在'std :: cin'上调用一个流提取器将刷新'std :: cout'。 –

回答

3

我们来分析一下您的main功能:

cout<<"George 17\n"; 

此行打印"George 17"并切换到新的生产线。

string first_name="George"; 
int age=17; 

这定义变量first_name字符串初始化为"George"和可变age的整数初始化为17

cin>>first_name>>age; 

此读取string类型和int的输入(以该顺序),并将其保存到first_nameage。它不会提示你输入。 (你必须使用cout来实现它。)它只是等待你提供输入。这可能看起来像你喜欢的程序完成。但事实并非如此。

cout<<"Hello,"<<first_name<<"(age"<<age<<")\n"; 

此行将最终打印您的预期输出。