There is a format string "123,456,123,23,789,67" . 6 numbers separated by commas. It is necessary to get the last 2 numbers into variables of type int .

The problem is solved easily with sscanf() :

 #include <stdio.h> int main(int argc, char* argv[]) { char buf[] = "123,456,123,23,789,67"; int a1, a2, a3, a4, a5, p1, p2; sscanf(buf, "%d,%d,%d,%d,%d,%d", &a1, &a2, &a3, &a4, &p1, &p2); return 0; } 

Question: How to solve this problem using iterators and string class methods?

  • Do you read this line from the user? Or written in advance? - Herrgott

2 answers 2

For starters, you can break a string into substrings. Options for the implementation of this (in fact - the method of split ) - the car and a small truck. Let me give you one, quite primitive, for example:

 #include <sstream> #include <string> #include <vector> std::vector<std::string> split(std::string & s, char delimeter) { std::stringstream ss(s); std::string item; std::vector<std::string> tokens; while (std::getline(ss, item, delimeter)) { tokens.push_back(item); } return tokens; } 

Respectively,

 std::string s("123,456,123,23,789,67"); std::vector<std::string> tokens = split(s, ','); 

Well, what to do with the resulting vector is already creative :)

  • Thank! Everything turned out to be quite simple and obvious. - dmk
  • @Pink Tux: Why exactly std::vector can better std::forward_list ? - sys_dev

If you want to get the last few numbers, then it is logical to read from the end, so as not to process potentially unnecessary data.

 #include <string> #include <iostream> int main() { const std::string buf = "123,456,123,23,789,67"; size_t ppos = std::string::npos; do { size_t pos = buf.find_last_of(',', ppos - 1); int v = stoi(buf.substr(pos + 1, ppos - (pos + 1))); std::cout << v << "\n"; // 袠褋锌芯谢褜蟹褍械屑 `v` 锌芯 薪邪蟹薪邪褔械薪懈褞 ppos = pos; } while( ppos != std::string::npos ); } 

View result

After obtaining the necessary amount of data, the cycle can be interrupted.

  • one
    stoi() is starting with C ++ 11 - avp
  • @avp yes. And I have 2016 on the calendar. And you? :) - 伪位蔚蠂慰位蠀蟿
  • one
    Me too. Only now (at least in Ubuntu 16.04 LTS (not to mention the earlier ones (14.04 LTS will be supported until the 19th)) for g ++ even in the new version 5.3.1 -std = by default - gnu++98 gnu++03 GNU dialect of -std=c++98. This is the default for C++ code. gnu++98 gnu++03 GNU dialect of -std=c++98. This is the default for C++ code. So even the 11th, it will not be very urgent everywhere. - avp
  • one
    Passing the key to the @avp compiler is not such a big problem. Well, if only for completely lazy :) If there was no support for c++11 at all, then there would be a different conversation. - 伪位蔚蠂慰位蠀蟿
  • one
    Well, so that the key was added, I wrote a comment. - avp