Help understanding snippet

Prof give sample code, but do not understand what's going on up in here:

Entire code at bottom;


questions in the comments within code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 int lettercount [LETTERS];

   for(int i = 0; i < LETTERS; i++)

       lettercount[i] = 0;

  lettercount[tolower(str.at(0)) - tolower('a')]++; //

// what is going on with the str.at(0) - tolower('a')  | why would
// or could you substract a letter from a string at the beginning?

   for(int i = 0; i < LETTERS; i++)

      cout << lettercount[i] << " "

         << static_cast<char>(i + tolower('a')) << endl; //
//  he does here again.  he adds a tolower('a') to i for some reason.
//  also, what is the static_cast<char> before this?  it looks like a function, 
//  but what is the < > ? it reads a type?   







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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
  #include <iostream>
#include <cstdlib>
#include <string>
#include <sstream>
#include <cctype>

using namespace std;

const int LETTERS = 26;

string user_input();
void new_line();

int main( )

{

	string str =  "";

	//input user string

	str = user_input();
	
   //string str = "I say Hi.";

   int lettercount [LETTERS];

   for(int i = 0; i < LETTERS; i++)

       lettercount[i] = 0;

  lettercount[tolower(str.at(0)) - tolower('a')]++;

   for(int i = 0; i < LETTERS; i++)

      cout << lettercount[i] << " "

         << static_cast<char>(i + tolower('a')) << endl;
			
		cin.get();
		//return 0;

}


string user_input()

{

	string input = "";
	char ans;
	do {
	cout << "Please input a word or sentence you wish to break down.\n>" ;

	getline(cin, input);
	cout << "You wrote:  " <<  input << endl;
	cout << "Is this correct?\n>";
	cin >> ans;
	new_line();

	} while (ans != 'Y' && ans != 'y');
	return input;
}

void new_line()
{
	char symbol;
	do {
		cin.get(symbol);
	} while (symbol != '\n');

}
First question, this is just mapping each letter to an index in the lettercount array so 'a' is mapped to 0, 'b' to 1 and so on.

The way it maps the letters to an index is by using ascii codes because every letter is represented by a number, google ascii table to see it and better understand this.

'a' has a code (value) and 'b' has 'a' value + 1 and so on to 'z'

The same goes for the second question this time he is mapping indecies to letters so 0 becomes 'a' and so on, all what static_cast in this code does is that it converts the given number to a char according to ascii table.

You can read more about casting here : http://www.cplusplus.com/doc/tutorial/typecasting/
and more about ascii codes here : http://www.cplusplus.com/doc/ascii/ and http://www.asciitable.com/
Last edited on
Thanks, very helpful.

Topic archived. No new replies allowed.