First, I need to create a bool that returns true if a string has no space and false if it does. I think I have this correct.
Then, I need to create a function that gets words from the user and compares it to the bool, then outputs the length of the largest word.
The only problem is that wherever I place the bool function, it doesn't work or the whole thing won't run.
#include <iostream>
#include <string>
usingnamespace std;
bool IsAWord (string s) {
int y=0,q=0;
while (y<s.length()) {
if (s[y]==' ') {q++;}
y++;
}
if (q=0) {returntrue;}
else {returnfalse;}
}
int main () {
cout << "Enter 5 words and the longest word will be given. \n";
int N=1;
int longest=0;
string s;
while (N<6) {getline (cin,s);
if (IsAWord(s)=true) {if (longest==0)longest=s.length();
elseif (longest<s.length()) {longest=s.length();}
N++;}}
cout << "The longest actual word is: " << longest << "letters long.";
system ("pause");
}
That's what I think it should be (bolded part), but it's obviously not because the program will give an error if I try to do that.
First, I need to create a bool that returns true if a string has no space and false if it does. I think I have this correct.
I think that where you use 'bool' you mean to use 'function which returns a boolean'.
Caith wrote:
5 6 7 8 9 10 11 12 13
bool IsAWord (string s) {
int y=0,q=0;
while (y<s.length()) {
if (s[y]==' ') {q++;}
y++;
}
if (q=0) {returntrue;}
else {returnfalse;}
}
Firstly, you're assigning 0 to q, not comparing 0 to q. Secondly, if your goal is to return false if there is a space and true otherwise, can't you just return false as soon as the space is discovered and return tru after the loop is over?
is attempting to assign the value true to a function, which doesn't make sense to the compiler. Try this: if (IsAWord(s) == true) {
or better yet: if (IsAWord(s)) {
EDIT: You can also save yourself a little tortured logic by leveraging some of the built-in string functionality:
1 2 3 4 5
bool isAWord(const std::string s)
{
//returns true if no space is found in the string
return ( s.find(' ') == std::string::npos );
}