c++ - 在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;
}
解决方案
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';
}
推荐阅读
- c - 循环直到用户输入'x'
- json - 我在 3d 场景中加载 3d 对象(json 文件)时遇到问题
- r - R - 根据 ID 向量中包含的文本合并两个数据帧
- javascript - 允许导入的 Webpack 配置
- html - 文本在垂直方向上没有完全居中,因为字体的后代稍大
- c - 从 scanf 切换到 fgets & Char 到 Int - 卡在 while statment
- python - python html.select 返回无
- node.js - 将 json 响应添加到 Map 字段 Mongoose 节点
- java - 如何将 Flux 或 Mono 发送到模板 (Freemaker)
- python - 更简化的计算文件行数的方法(python)