substring counter not working

I've made a program that counts the number of times a substring appears within a string.It works just fine if the string has no spaces but if it has any it doesn't count the substrings after the first space.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include<iostream>
#include<string>
using namespace std;

int main()
{
    int count = 0;
    string x;
    cin >> x;
    for (int i = 0; i < x.size() - 1; i++) {
        if ( x.substr(i,2) == "am") count++;
    }
    cout << count;
    return 0;
}


Is it that size() only tells you the size of the string until it "hits" a space?If yes then how do I get the actual length of a string?
Last edited on
1
2
    string x;
    cin >> x;

Does first discards all leading whitespace. Then it reads characters until next whitespace. In other words, it reads "only one word".

You have to use std::getline if you want to read "multi-word" text.
http://www.cplusplus.com/reference/string/string/getline/


Consider also string::find. http://www.cplusplus.com/reference/string/string/find/
1
2
3
4
5
6
std::string token = "am";
std::size_t found = x.find( token );
while ( found != std::string::npos ) {
  ++count;
  found = x.find( token, found + 1 );
}
The problem is with the stream extraction. >> only extracts to a white-space char (space, tab, \n). To obtain all of the input line, use getline:

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()
{
	int count = 0;
	string x;

	//cin >> x;
	getline(cin, x);

	for (int i = 0; i < x.size() - 1; i++) {
		if (x.substr(i, 2) == "am")
			count++;
	}

	cout << count;
	return 0;
}



thanks a lot It's working now!
Topic archived. No new replies allowed.