How to make a loop in a strlen?

Define a string, then create a program that asks a user to enter something, then displays the number of characters entered with the message:

You entered XX Characters.

This should be a loop that ends when the user enters “stop” in lower case.
Hint (strlen) Having trouble with the loop 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




#include <iostream>
#include <cstring>
using namespace std;
int main()

{
	char stuff[50];
	int length=0;
	cout << "Please Enter something:" ;
	cin >> stuff;
	length = strlen(stuff);
	for (index = 0; index < stuff index++)
	{
		if (stuff != "stop")
			break;
		else
			cout << "\nThe number of chracters entered was " << length << endl;

	}

	system("Pause");
	return 0;
}
Last edited on
This code isn't using strlen. That's a function for c-strings but your code uses C++ std::string. The correct header for std::string is #include <string>

You didn't say what the purpose of the loop would be. You can learn about loops here:
http://www.cplusplus.com/doc/tutorial/control/

http://www.cplusplus.com/reference/cstring/strlen/
http://www.cplusplus.com/reference/string/string/size/
sry I used the wrong project to copy/paste my code this is the one i'm working on
The code won't compile as-is.

if (stuff != "stop") // line 22

You cannot use a comparison like this with a c-string. (though it would be valid for a std::string).

To compare c-string stuff with "stop" here, use strcmp().

http://www.cplusplus.com/reference/cstring/strcmp/

Note that there is an example of a do-while loop given on the above reference page for strcmp, which may be similar to what you want. It repeats until the user enters "apple".


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstring>

using namespace std;

int main()
{
    char stuff[50];
    
    cout << "Please Enter something: " ;
    cin >> stuff;
        
    if (strcmp(stuff,"stop") == 0)
        cout << "\nstuff is equal to 'stop'\n";
    else
        cout << "\nThe number of characters entered was " << strlen(stuff) << '\n';
    
}
Last edited on
thanks! strcmp and that link really helped me, how would i define a string if there wasn't a array number??
Topic archived. No new replies allowed.