繁体   English   中英

意外的cin行为

[英]Unexpected cin behavior

我正在编写一个函数int count_words(string str) ,该函数返回int count_words(string str)中所有单词的计数。

问题是无论输入什么,结果都是1。有人可以帮忙吗?

#include <iostream>
#include <string>

using namespace std;

int count_words(string str)
{
    int i,j;
    j = 1;
    int l = str.length();
    for(i = 0; i < l; i++)
    {
        string c = str.substr(i,1);
        if(c == " ")
        {
            j++;
        }
    }
    cout << "The total word in the string: " << j << endl;
    return j;
}


int main()
{
    string str;
    cout << "Please enter a string: ";
    cin >> str;
    int result = count_words(str);
    return 0;
}

如果字符串中包含空格,则应使用cin.getline ,因为将>>运算符与cin只能读取下一个空格

看到std :: cin输入有空格吗?

考虑遍历字符串:

auto cstyle= str.c_str();
for (int i = 0; i < str.length(); ++i)
{
  if (cstyle[i]==' ')//assumes words are delimited by a single space
  {
    j++;
  }
}

您应该使用: cin.getline ,例如:

int main()
{
    cout << "Please enter a string: ";
    unsigned size=10;
    char*chr=new char[size];
    cin.getline(chr,size);
    string str(chr);
    //cin >> str;
    int result = count_words(str);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM