2011-09-28 63 views

回答

1

std::istream::getline(char *, streamsize)

被盜無恥地從http://www.cplusplus.com/reference/iostream/istream/getline/

// istream getline 
#include <iostream> 
using namespace std; 
int main() { 
    char name[256], title[256]; 

    cout << "Enter your name: "; 
    cin.getline (name,256); 

    cout << "Enter your favourite movie: "; 
    cin.getline (title,256); 

    cout << name << "'s favourite movie is " << title; 

    return 0; 
} 
+1

然後有人輸入超過256個字符的行... – Sjoerd

+0

什麼樣的麻煩?而且,你爲什麼要衝洗輸入流? –

1

通過使用std::string。沒有理由不使用它。

如果在某種模糊的機會下,您有額外的要求,爲什麼您不能使用std::string,請說明這些要求,因爲它們會影響代碼。

更新:如果輸入的是換行符分隔,使用string s; std::getline(cin, s);

+1

這個問題非常清楚地表明不使用字符串類。 – Mysticial

+2

@Mysticial那麼?如果OP指出**爲什麼**他不能使用字符串類,我們可能會在他的思想中發現錯誤。也許OP錯誤地認爲'cin >> s'是唯一的輸入'std :: string'的方法,在這種情況下,我的答案將解決他的問題。 – Sjoerd

相關問題