2013-11-21 66 views
0

我正在設計一個具有1個輸入參數的函數:字符串。該函數獲取此字符串的內容,並將每個單詞輸出到一個新行。目前,這個函數除了輸出字符串中的最後一個單詞之外,其他的都會完成。下面是功能代碼:將字符串中的每個單詞輸出到一個新行

void outputPhrase(string newPhrase) 
{ 
    string ok; 
    for (int i = 0; i < newPhrase.length(); i++) 
    { 
     ok += newPhrase[i]; 
     if (isspace(newPhrase.at(i))) 
     { 
      cout << ok << endl; 
      ok.clear(); 
     } 
    } 
} 

回答

1

試試這個:

for (int i = 0; i < newPhrase.length(); i++) 
    { 
     ok += newPhrase[i]; 

     if (isspace(newPhrase.at(i)) || i==newPhrase.length()-1) 
     { 
      cout << ok << endl; 

      ok.clear(); 

     } 


    } 
+0

我的版本檢查是否isspace或if是否已達到字符串的末尾 –

1

您可以使用此函數來完成你的任務,

void split(string newPhrase) 
{ 
    istringstream iss(newPhrase); 

    do 
    { 
     string sub; 
     iss >> sub; 
     cout << sub << endl; 
    } while (iss); 
} 

請記住,包括<字符串>和< sstream>中你的代碼。

+1

+1使用stringstream – smac89

相關問題