【发布时间】:2021-01-22 19:31:57
【问题描述】:
这个代码应该说明一个词是否出现在一个句子中。当我在声明字符串的位置插入句子和单词时(例如:string s = "the cat is on the table" string p = "table" 程序说这个词在句子中)代码有效,但是,使用 getline,for 循环永远不会开始,它总是说单词不在句子中。
请帮助我不知道该怎么办
#include <iostream>
#include <string>
using namespace std;
int main () {
string s;
string p;
string word;
bool found = false;
int sl = s.length();
int beg = 0;
int pl = p.length();
cout << "sentence: ";
getline(cin, s);
cout << "word: ";
getline(cin, p);
for(int a = 0; a<sl; a++)
{
if(s[a]== ' ')
{
word = s.substr(beg, a-beg);
if (word== p)
{
found = true;
break;
}
beg = a+1;
}
}
if (found== true)
{
cout <<"word " << p << " is in a sentence " << s;
}
else
{
word = s.substr(beg);
if (word== p)
{
found = true;
}
if(found == true)
{
cout <<"the word " << p << " is in the sentence " << s;
}
else
{
cout <<"the word " << p << " isn't in the sentence " << s;
}
}
}
【问题讨论】:
-
你需要计算
sl之后你getline字符串s。否则sl只是默认字符串的大小,即 0,因此您永远不会进入循环。