How do I properly call in a bool?

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.

This is what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
using namespace std;

bool IsAWord (string s) {
	int y=0,q=0;
	while (y<s.length()) {
		if (s[y]==' ') {q++;}
		y++;
	}
	if (q=0) {return true;}
	else {return false;}
}

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();
		else if (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.
Caith wrote:
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) {return true;}
	else {return false;}
}
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?
Line 21
 
if (IsAWord(s)=true) {
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 );
}

Last edited on
Wow thanks, I didn't notice some of the things I shouldn't have messed up.
Topic archived. No new replies allowed.