Need help using pointers.

Oct 11, 2015 at 3:54pm
Could someone help me to determine what I am doing wrong in my program. I am trying to use pointers to count the numbers of words in a given string.

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
#include <iostream>
using namespace std;

int findWord(char *str, int size);

int main()
{
	char str[100];

	cout << "Enter a sentence: " << endl;
	cin >> str;
	
	int words = findWord(str, 99);

	cout << "There are " << words << " words in the sentence " << endl;

	return 0;
}
int findWord(char *str, int size)
{
	int count = 0;
	
	while (*str)
	{
		if (*str == ' ')
			count++;
	}
	return count;
}
Oct 11, 2015 at 3:59pm
What's doing?
Error messages?
Oct 11, 2015 at 4:03pm
The program is able to compile, but when I input a sentence, it just goes down the the next line. I think my error is within the function.
Last edited on Oct 11, 2015 at 4:03pm
Oct 11, 2015 at 4:04pm
Your while loop is infinite because you never do anything that could make the condition false. Maybe you meant to increment the pointer?
Oct 11, 2015 at 4:22pm
seems like you don't really understand howwhile works

try this:
1
2
3
4
5
6
7
8
9
10
11
12
int findWord(char *str, int size)
{
	int count = 0;
	
	while (count < size)
	{
		if (condition_are_met)
			break;
		++count;
	}
	return count;
}
Topic archived. No new replies allowed.