I am trying to use the std::map template, but I haven’t been able to get it working. From research on the internet I’ve come to this solution and redirecting the a file to the input stream, here is the code:
typedef map<char*, int> wc;
int main() {
int c;
char cc[75], nombre[75];
wc m;
scanf("%d", &c);
while (c--) {
scanf("%s %[ a-zA-Z]", cc, nombre);
++m[cc]; // This should work
printmap(m);
}
}
Print map is a function that just prints the map object. Here is my file input.txt
3
Spain Donna Elvira
England Jane Doe
Spain Donna Anna
When I execute the program, the ouput is:
Spain -> 1
England -> 2
Spain -> 1
What I expect is:
Spain -> 2
England -> 1
The number of occurrences of the Country mapped to the number of times it appears
As a solution to my comment above, the C++ version of the code you presented:
http://ideone.com/2JP82
First:
std::mapsorts it’s data based on the key, in your code,char*, which points atchar cc[75]. So when you replaced the text incc, then the keys of the map changed, and that breaks everything. The keys of a map must not change ever. Since we’re using C++, you should not usechar[]at all; usestd::stringinstead, which (since it is a “value type”) will make everything just magically work. I have no idea how it was working before, since you don’t show theprintmapfunction.Second: You call
printmapeach and every time you read a single line, and since amaphas no way of printing “the last thing added”, that idea makes no sense at all. Theprintmapcall should probably print the entire map, and be outside the loop.Third: Don’t use
scanf, it’s not safe. Use streams:std::cin >> ccfor reading in a single word, orstd::getline(std::cin, nombre)for reading in what’s left on the line. That way the code won’t crash if someone enters the line (sources for longest country name and longest last name)