在实现一个家庭作业问题的逻辑方面存在一些问题。我目前使用的平台是Visual Studio 2013,我是初学者。我们使用应用程序内置的终端(命令提示符)来获取输入和输出。我们目前正在使用“CIN”和“COUT”。问题如下:
“编写一个程序,要求用户输入一个句子,然后删除每个偶数字。例如:”All The Presidents Men“将成为”All Presidents“。将修改后的句子返回给main()函数输出参数,然后显示原始和修改的句子“。
我一直在尝试将逻辑应用于将每个单词放入数组/向量中,并使用偶数索引删除每个单词。我还没有成功完成这项工作,我正在向您寻求专家的帮助!
非常感谢。
答案 0 :(得分:1)
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;
}
}
答案 1 :(得分: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++;
}`