2016-03-01 58 views
-1

在實現一個作業問題的邏輯時遇到了一些問題。我目前使用的平臺是Visual Studio 2013,是初學者。我們使用應用程序內置的終端(命令提示符)來獲取輸入和輸出。我們目前正在使用「CIN」和「COUT」。問題如下:C++從字符串中刪除偶數編號的字

「編寫一個程序,要求用戶輸入一個句子,然後去掉每一個偶數字,例如:」All The Presidents Men「將成爲」All Presidents「。使用輸出參數對main()函數進行判斷,然後顯示原始語句和修飾語句「。

我一直在試圖應用這種邏輯,把每個單詞放入一個數組/矢量,並刪除每個單詞的偶數索引。我尚未成功完成此任務,並正在尋求專家的幫助!

非常感謝。

+0

請更具體一點什麼你都試過,什麼問題(例如,通過向我們展示你的代碼)。 – MikeMB

回答

0

你可以寫這樣的事情

int count = -1; 
for (auto it =input.begin();it!=input.end();){ 
if(*it==' '){ 
    count++;it++; 
    if (count%2==0){ 
     while (it != input.end()){ 
      if (*it==' ')break; 
      it=input.erase (it); 
     } 
    }else it++; 
}else it++; 
}` 
1

Live Demo

std::string line; 

// get input from cin stream 
if (std::getline(cin, line)) // check for success 
{ 
    std::vector<std::string> words; 
    std::string word; 

    // The simplest way to split our line with a ' ' delimiter is using istreamstring + getline 
    std::istringstream stream; 
    stream.str(line); 

    // Split line into words and insert them into our vector "words" 
    while (std::getline(stream, word, ' ')) 
     words.push_back(word); 

    if (words.size() % 2 != 0) // if word count is not even, print error. 
     std::cout << "Word count not even " << words.size() << " for string: " << line; 
    else 
    { 
     //Remove the last word from the vector to make it odd 
     words.pop_back(); 

     std::cout << "Original: " << line << endl; 
     std::cout << "New:"; 

     for (std::string& w : words) 
      cout << " " << w; 
    } 
}