gpt4 book ai didi

c++ - std::cin 跳过空格

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:02:42 25 4
gpt4 key购买 nike

因此,我正在尝试编写一个函数来检查一个单词是否在一个句子中,方法是遍历一个 char 数组并检查相同的 char 字符串。只要 Sentence 没有任何空格,该程序就可以运行。我用谷歌搜索,它们都是相同的建议;

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 进行比较。

最佳答案

好的,我会尽力解释你的问题:

假设这是您的输入:

thisisaword
this is a sentence

当您使用 cin 并为其提供任何输入时,它会在换行符处停止,在我的示例中,换行符跟在“thisisaword”中的字符“d”之后。
现在,您的 getline 函数将读取每个字符,直到它停止换行符。
问题是,getline遇到的第一个字符已经是一个换行符,所以它会立即停止。

这是怎么回事?

我会试着这样解释:

如果这是您给程序的输入(注意\n 字符,将其视为单个字符):

thisisaword\n
this is a sentence\n

你的 cin 函数将接受和离开什么:

\n
this is a sentence\n

现在 getline 看到这个输入并被指示获取每个字符,直到它遇到一个换行符,即“\n”

\n <- Uh oh, thats the first character it encounters!
this is a sentence\n

cin 读取输入并留下“\n”,其中 getline 包含“\n”。

要克服这个问题:

\n <- we need to get rid of this so getline can work
this is a sentence\n

如前所述,我们不能再次使用 cin,因为它什么都不做。我们可以使用不带任何参数的 cin.ignore() 并让它从输入中删除第一个字符或使用 2x getline(第一个将获取剩余的\n,第二个将获取带有\n 的句子)

你也可以避免这种问题切换你的cin >> Word;到 getline 函数。

因为它被标记为 C++,所以我将 Char*[] 更改为 Strings 以用于此示例:

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;

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;

关于c++ - std::cin 跳过空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27205251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com