所以我试着通过循环char数组并检查相同的char字符串来编写一个函数来检查一个单词是否在一个句子中.只要句子没有任何空格,该程序就可以运行.我用Google搜索,他们都是一样的建议;
cin.getline
Run Code Online (Sandbox Code Playgroud)
但是,无论我实现它,它要么不运行,要么跳过整个输入并直接输出.
我怎么能占空间?
#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;
}
Run Code Online (Sandbox Code Playgroud)
并且我不允许使用strstr进行比较.
Pat*_*zyk 14
好的,我会尝试解释你的问题:
我们假设这是您的输入:
thisisaword
这是一个句子
当你使用cin并给它任何输入时,它会停止在换行符中,在我的例子中,在'thisisaword'中跟随字符'd'.
现在,你的getline函数将读取每个字符,直到它停止换行符.
问题是,遇到第一个字符的getline已经是换行符,所以它会立即停止.
这是怎么回事?
我会试着这样解释一下:
如果这是您给予程序的输入(注意\n字符,请将其视为单个字符):
thisisaword \n
这是一句话\n
你的cin功能将带走和离开:
\n
这是一句话\n
现在getline看到了这个输入,并被指示获取每个字符,直到它遇到换行符"\n"
\n < - 哦,这就是它遇到的第一个角色!
这是一句话\n
cin读取输入并离开"\n",其中getline包含"\n".
要克服这个:
\n < - 我们需要摆脱这个,所以getline可以工作
这是一个句子\n
如上所述,我们不能再使用cin,因为它什么也不做.我们可以使用没有任何参数的cin.ignore()并让它从输入中删除第一个字符或使用2x getline(第一个将取剩余的\n,第二个将使用\n的句子)
你也可以避免这种问题切换你的cin >> Word; 到getline函数.
由于这被标记为C++,因此我将Char*[]更改为字符串:
string Word, Sentence;
cout << "Please enter a word: "; cin >> Word;
cout << endl << Word;
cin.ignore();
cout << "\nPlease enter a sentence: "; getline(cin, Sentence);
cout << endl << Sentence;
Run Code Online (Sandbox Code Playgroud)
要么
string Word, Sentence;
cout << "Please enter a word: "; getline(cin, Word);
cout << endl << Word;
cout << "\nPlease enter a sentence: "; getline(cin, Sentence);
cout << endl << Sentence;
Run Code Online (Sandbox Code Playgroud)
怎么样使用这个:
std::cin >> std::noskipws >> a >> b >> c;
Run Code Online (Sandbox Code Playgroud)
cin默认使用这样的东西:
std::cin >> std::skipws >> a >> b >> c;
Run Code Online (Sandbox Code Playgroud)
你可以结合旗帜:
std::cin >> std::skipws >> a >> std::noskipws >> b;
Run Code Online (Sandbox Code Playgroud)
告诉我它是否适合你:)
默认情况下 operator>> 跳过空格。您可以修改该行为。
is.unsetf(ios_base::skipws)
Run Code Online (Sandbox Code Playgroud)
将导致is's >> operator将空白字符视为普通字符。