How do I find the number of characters in a word in a string?

I want to take a string, find a word that the user searches for and also find the number of characters in that word.

Here's what I have so far. I omitted some parts of the program that were not relevant to the issue I'm having here.

So if the user typed the sentence The spice must flow. and then searched for must they would get a result of 4.

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

using namespace std;

int main (){

	cout << "Enter a sentence: ";
	string mysentence;
	getline (cin,mysentence);

	cout << "Enter a search term: ";
	string mysearchTerm;
	getline (cin,mysearchTerm);
		
	cout << "Found the word " << mysearchTerm << " at position " << mysentence.find(mysearchTerm) << endl;
	cout << "This word has a length of " << mysentence.length()   << " characters." << endl;

}


I'm very new to C++ so thanks in advance for the help!
Last edited on
mystringname.size() returns the quantity of characters
Like this?

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

using namespace std;

int main (){

	cout << "Enter a sentence: ";
	string mysentence;
	getline (cin,mysentence);

	cout << "Enter a search term: ";
	string mysearchTerm;
	getline (cin,mysearchTerm);
		
	cout << "Found the word " << mysearchTerm << " at position " << mysentence.find(mysearchTerm) << endl;
	cout << "This word has a length of " << mystringname.size(mysearchTerm)   << " characters." << endl;

}
Last edited on
Perhaps you mean mysearchTerm.size()? (when I said mystringname, I meant for you to replace that with your string name)
Last edited on
I got it working. Thanks!
Topic archived. No new replies allowed.