I am writing a function int count_words(string str)
that returns a count of all of the words in the string.
The issue is that regardless of the input, the result is 1. Can anyone help?
#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
只能读取下一个空格
See std::cin input with spaces?
Consider iterating over the string:
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++;
}
}
You should use: cin.getline
, for example:
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.