【发布时间】:2015-01-28 02:13:08
【问题描述】:
所以我正在尝试编写一个函数来检查一个单词是否在一个句子中,通过循环遍历一个 char 数组并检查相同的 char 字符串。只要句子没有任何空格,该程序就可以工作。我用谷歌搜索了一下,它们都是相同的建议;
cin.getline
但是无论我如何实现它,它要么不运行,要么跳过整个输入并直接进入输出。
如何计算空间?
#include <iostream>
using namespace std;
bool isPartOf(char *, char *);
int main()
{
char* Word= new char[40];
char* Sentence= new char[200];
cout << "Please enter a word: ";
cin >> Word;
cout << endl << "Please enter a sentence: ";
//After Word is input, the below input is skipped and a final output is given.
cin.getline(Sentence, 190);
cout << endl;
if (isPartOf(Word, Sentence)==true)
{
cout << endl << "It is part of it.";
}
else
{
cout << endl << "It is not part of it.";
}
}
bool isPartOf(char* a, char* b) //This is the function that does the comparison.
{
int i,j,k;
for(i = 0; b[i] != '\0'; i++)
{
j = 0;
if (a[j] == b[i])
{
k = i;
while (a[j] == b[k])
{
j++;
k++;
return 1;
if (a[j]=='\0')
{
break;
}
}
}
}
return 0;
}
而且我不允许使用 strstr 进行比较。
【问题讨论】:
-
使用
std::getline()和std::istringstream到底有什么问题? -
它从不要求输入句子。这是运行代码时 cmd 的样子。 LINK