Is there a way to cast on the map?

I have a file with entries on the map, separated by a line, and the keys and values ​​are separated by the symbol ':' So something like:

one: 1
two: 2
three: 3
four: 4

I open this in an ifstream called dict and run the following code:

string key, value; map< string, int > mytest; while( getline( dict, key, ':' ).good() && getline( dict, value ).good() ) { mytest[key] = atoi( value.c_str() ); } 

Is there a better way to do this? Is there any getline functionality that will skip spaces from the key? (I'm trying to do this without promotion.)

+4
source share
2 answers

@Jonathan Mee: Actually your post is very elegant (you may have problems if the parsing format does not match). Therefore, my answer is: there is no better way. +1

Edit:

 #include <iostream> #include <map> #include <sstream> int main() { std::istringstream input( "one : 1\n" "two : 2\n" "three:3\n" "four : 4\n" "invalid key : 5\n" "invalid_value : 6 6 \n" ); std::string key; std::string value; std::map<std::string, int > map; while(std::getline(input, key, ':') && std::getline(input, value)) { std::istringstream k(key); char sentinel; k >> key; if( ! k || k >> sentinel) std::cerr << "Invalid Key: " << key << std::endl; else { std::istringstream v(value); int i; v >> i; if( ! v || v >> sentinel) std::cerr << "Invalid value:" << value << std::endl; else { map[key] = i; } } } for(const auto& kv: map) std::cout << kv.first << " = " << kv.second << std::endl; return 0; } 
+2
source

Yes, you can just drop the colon into the garbage variable

 string key, colon; int value; while(cin >> key >> colon >> value) mytest[key] = value; 

Thus, you must make sure that the colon is separated by a space, and that your key does not contain spaces. Otherwise, it will be read inside the key string. Or your part of the line will be read as a colon.

+3
source

Source: https://habr.com/ru/post/1502649/


All Articles