Can't run a program about string.

closed account (oLC9216C)
The code works, but after I run the exe file, no response.
I am trying to read a line, and count how many times does the leeter show up in the sentence.

1
2
3
4
5
6
7
8
9
10
11
    for(int x = 0;x<range;x++) //range is 26, from a-z.
    {
        for(int i = 0; x << line.size();i++) // line is the sentence
        {
            if(eng[x]==line[i] || eng[x]-32 == line [i]) 
            num_eng++;
        }
    if(num_eng > 0)
        cout << eng[x] << num_eng << endl;
    num_eng = 0;
Last edited on
If you're trying to count the number of times a letter shows up in a string. I suggest using a std::map.

line 3: should be for (int i = 0; i < line.size(); ++i)
closed account (oLC9216C)
97 is 'a' and 65 is 'A'
in line 5,
am i doing it right?
You're doing it much more complicated that it has to be :)
consider this:
1
2
3
4
string my_test = "There Was A Duck Named Bills";

for (unsigned i = 'a'; i <= 'z'; ++i) {
}


That is a nice loop that will get you from a to z. But only in lowercase, so when you're checking a value of your string just pass it to tolower(char)


closed account (oLC9216C)
to use tolower(char) what library should I include?
I believe it's auto included when you include <string>
closed account (oLC9216C)
There is an error : no matching function for call to 'tolower(std::string&)'|

I just added
tolower(line);

std::tolower is declared in <cctype>.
closed account (oLC9216C)
still have the same error, is there any example of using tolower?
Here is the test code I used to test my logic
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
31
32
33
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>

using namespace std;


bool converToInt(const string& value, int &result) {
	stringstream s(value);
	if ( !(s >> result) || s.peek() != (int)string::npos)
		return false;

	return true;
}


int main() {

	string my_test = "There was a duck named bill";

	for (unsigned i = 'a'; i <= 'z'; ++i) {
		unsigned count = 0;
		for (unsigned j = 0; j < my_test.length(); ++j) {
			if (tolower(my_test[j]) == (char)i)
				count++;
		}
		cout << (char)i << " appeared " << count << " times" << endl;
	}


	return 0;
}
Topic archived. No new replies allowed.