【问题标题】:std::cin skips white spacesstd::cin 跳过空格
【发布时间】: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

标签: c++ cin spaces


【解决方案1】:

默认操作符>>跳过空格。您可以修改该行为。

is.unsetf(ios_base::skipws)

将导致is's &gt;&gt; operator 将空白字符视为普通字符。

【讨论】:

  • 我不完全确定如何使用该行。
【解决方案2】:

用这个怎么样:

std::cin >> std::noskipws >> a >> b >> c;

cin 默认使用这样的东西:

std::cin >> std::skipws >> a >> b >> c;

你可以组合标志:

std::cin >> std::skipws >> a >> std::noskipws >> b;

告诉我它是否适合你:)

【讨论】:

  • 所以如果我理解正确的话,我应该用“std::cin >> std::noskipws >> Sentence;”替换这一行?不幸的是,它仍然跳过输入:(
【解决方案3】:

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

假设这是您的输入:

这个词
这是一个句子

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

这是怎么回事?

我会试着这样解释:

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

这个单词\n
这是一个句子\n

你的 cin 函数会取走什么:

\n
这是一个句子\n

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

\n 这是一个句子\n

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

要克服这个问题:

\n 这是一个句子\n

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

你也可以避免这种切换cin>>字的问题;到 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;

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++ 新手,所以当向用户询问输入时,人们通常使用 getline 吗?
  • 它实际上取决于程序本身。初学者通常更喜欢使用 cin 或 scanf。 getline 主要用于读取文件并进行字符串操作。对我来说,大部分时间 cin 就足够了。
猜你喜欢
  • 2011-11-06
  • 2021-02-26
相关资源
最近更新 更多