首页 > 解决方案 > 在c ++中找到句子中的某个单词

问题描述

我想编写一个程序来查找用户输入的单词我认为我的解决方案是正确的,但是当我运行它时,程序在控制台中没有任何显示任何人都可以修复它?

int main()
 {
   char sen[200],del[200],maybedel[200];
   cout<<"enter sentence :"<<endl;
   cin.getline(sen,200);
   cout<<"which word do you want to delete ?";
   cin.getline(del,200);

   int len = strlen(sen);
   for(int i=0;i<=len;i++)
   {
    if(sen[i]==' ')
    {
        for(int j=i;j<=len;j++)
            if(sen[j]==' ' || sen[j]=='\0')
               for(int k=i+1,t=0;k<j;k++,t++)
                   maybedel[t]=sen[k]; 


    if(maybedel==del)
        cout<<maybedel;
    }
  }



return 0;
}

标签: c++stringsearchcharsentence

解决方案


The major reason for no output is

if (maybedel == del)  // <<< this will *never* be true
  cout << maybedel;   // will never run

Since comparing "strings" in arrays needs help from std::strcmp(maybedel,del) == 0 would be better.

UPDATE:

Another attack method is to avoid raw loops and utilize the STL to your favor. Here's a more robust solution:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
using namespace std;
int main() {
    cout << "enter sentence :\n";
    string sen;
    if (!getline(cin, sen)) throw std::runtime_error("Unable to read sentence");
    cout << "which word do you want to delete ? ";
    string del;
    if (!(cin >> del)) throw std::runtime_error("Unable to read delete word");
    istringstream stream_sen(sen);
    vector<string> arrayofkeptwords;
    remove_copy_if(istream_iterator<string>(stream_sen), istream_iterator<string>(),
                   back_inserter(arrayofkeptwords),
                   [&del](auto const &maybedel) { return maybedel == del; });
    copy(begin(arrayofkeptwords), end(arrayofkeptwords),
         ostream_iterator<string>(cout, " "));
    cout << '\n';
}

推荐阅读