C++ 从字符串中删除偶数编号的单词

C++ Remove Evenly numbered words from a string

本文关键字:编号 单词 删除 字符串 C++      更新时间:2023-10-16

在实现一个家庭作业问题的逻辑时遇到一些问题。我目前使用的平台是Visual Studio 2013,是初学者。我们使用应用程序内置的终端(命令提示符)来获取输入和输出。我们目前使用的是"CIN"和"COUT"。问题如下:

"编写一个程序,要求用户输入一个句子,然后去掉每个偶数单词。例如:"所有总统男人"将变成"所有总统"。使用输出参数将修改后的句子返回到 main() 函数,然后显示原始句子和修改后的句子"。

我一直在尝试将其应用于将每个单词放入数组/向量的逻辑中,并删除每个具有偶数索引的单词。我还没有成功地做到这一点,正在向你们的专家寻求一些帮助!

多谢。

现场演示

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;
    }
}

你可以写这样的东西

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++;
}`