2017-08-03 19 views

回答

1

我是那種你問這裏是什麼的困惑,但我在這裏發現了一些可以被固定。

是的代碼,你編譯和它的作品。但是,它可以改進。 當系統提示您輸入一些東西給你的char數組時,你會注意到它不接受空格。所以如果我輸入,Jon Smith,輸出將只是Jon和其餘的字符串輸入被切斷。要解決這個問題,您需要撥打getline()函數。

documentation of getline()狀態:從

提取字符是並將其存儲到STR直到劃界字符DELIM被發現(或換行字符, '\ N' ..)

這將允許您從輸入中獲取空格,並將整個輸入放回string

如果此函數調用添加到您的代碼,其中第二輸入提示的謊言和你運行代碼,你會發現,你將只能得到提示一次,然後程序會完成第二提示符之前運行出現被執行。這是因爲getline()不會忽略前導空白字符,並且因爲它被視爲換行符之前的cin>>而停止讀取。

要使getline()cin>>一起使用,您必須在致電getline()之前使用cin.ignore()。以下是我編寫的一些代碼,用於進行此調整:

// Example program 
#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    int n; 
    string s; //using string allows us to use getline() 

    cout<<"Enter a number: "; //Let user know they are being prompt for number 
    cin>>n; 
    cin.ignore(); //ignore the leading newline 

    cout<<"Enter a string: "; //let user know being prompt for string 
    getline (cin,s); 

    cout<<n*2<<"\n"; 
    cout<<s; 
    return 0; 
} 

再次,您已經工作和編譯的代碼。我不確定我的解決方案是否是您希望獲得的答案,但我希望您能找到這個有用的答案!乾杯!

+0

當然..謝謝..:D – Koran

相關問題