2013-03-27 105 views
1

我想學習C++。我現在在線。 我已經寫了這個簡單的方法,應該要求輸入一個字符串,然後返回它。要做到這一點,我使用cin.getLine()方法,但我用cin.getLine字符串後不打印()cin.Getline什麼都不返回

string getString(char string[]) 
{ 

    cout << "Please enter a string to process "; 
    cin >> string; 
    cout << "String in getString before process: " << string << "\n"; 
    cin.getline(string, STRINGSIZE); 
    cout << "String after processing: " << string << "\n"; // here string is not printed 
    return string; 
} 

任何人可以幫助我瞭解我在做什麼錯?謝謝

+2

你怎麼稱呼這個功能? 'string'指向一個有效和足夠大的內存區域嗎?爲什麼符號名稱是'string',它只是把用'std :: string'看到你的代碼的人混淆了。這甚至編譯? – 2013-03-27 05:46:42

+0

爲什麼你從'cin'兩次讀取東西到'string'? – Mat 2013-03-27 05:48:02

+0

STRINGSIZE的價值是什麼,您的測試輸入是什麼? – MatthewD 2013-03-27 05:49:11

回答

2

你一讀串std::stringcin >> string;,然後再讀取cincin.getline(string, STREAMSIZE); 東西沒有必要,一旦閱讀並返回:

string getString(char string[]){ 
    cout << "Please enter a string to process "; 
    cin >> string; 
    cout << "String in getString before process: " << string << "\n"; 
    // process this, do whatever you describe as processing it 
    cout << "String after processing: " << string << "\n"; // string is printed 
    return string; 
} 

否則,如果你想使用getline,這樣做:

std::string name; 

    std::cout << "Please, enter your full name: "; 
    std::getline (std::cin,name); // or std::getline(std::cin,string, 'r'); to read 
    //only to delimiter character 'r' 
    std::cout << "Hello, " << name << "!\n"; 

所以要記住的事情是使用getline OR cin,不是b另外,除非真的有一些特別的原因,否則