2017-02-21 39 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"; 

此行將最終打印您的預期輸出。