Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 Project Euler Problem 22_学习 53 = 49714.

What is the total of all the name scores in the file?

 1 #include <iostream>
 2 #include <fstream>
 3 #include <string>
 4 #include <list>
 5 using namespace std;
 6 
 7 long GetValue(string s, int index)
 8 {
 9     long count = 0;
10     for(string::iterator it=s.begin(); it!=s.end(); it++)
11     {
12         if(*it >= 'A' && *it <= 'Z')
13         {
14             count += *it - 'A' + 1;
15         }
16     }
17 
18     return count * index;
19 }
20 
21 bool compare_nocase(string first, string second)
22 {
23   unsigned int i=0;
24   while ( (i<first.length()) && (i<second.length()) )
25   {
26     if(tolower(first[i])<tolower(second[i])) 
27     {
28         return true;
29     }
30     else if(tolower(first[i])>tolower(second[i])) 
31     {
32         return false;
33     }
34     ++i;
35   }
36 
37   if (first.length()<second.length()) 
38   {
39       return true;
40   }
41   else 
42   {
43       return false;
44   }
45 }
46 
47 int main()
48 {
49     ifstream myfile("e:\\names.txt");
50     string value;
51     int count = 1;
52     long long sum = 0;
53     list<string> names;
54     while(myfile.good())
55     {
56         getline(myfile, value, ',');
57         names.push_back(value);
58         //cout << value << endl;
59     }
60     names.sort(compare_nocase);
61     
62     for(list<string>::iterator it=names.begin(); it!=names.end(); it++)
63     {
64         sum += GetValue(*it, count++);
65     }
66 
67     cout << sum << endl;
68     cin.get();
69 }