1

I wanted to extract the values from the string in C++. I guess this is not the C++ way of doing this, but that one in particular doesn't work. Any ideas?

string line = "{10}{20}Hello World!"; int start; int end; string text; // What to use here? Is the sscanf() a good idea? How to implement it? cout << start; // 10 cout << end; // 20 cout << text; // Hello World! 
5
  • look at std::cin and string streams Commented Apr 30, 2017 at 20:00
  • Cin is to get values from 'keyboard', no? Commented Apr 30, 2017 at 20:01
  • 1
    Look up std::string::substr and/or std::regex Commented Apr 30, 2017 at 20:02
  • I know about substr, but it is pretty annoying/ugly to work with :/ Also, have had some problems with the pointers on that one :( Commented Apr 30, 2017 at 20:03
  • Can you provide a code sample of how to use regex in this particular example? Commented Apr 30, 2017 at 20:04

4 Answers 4

3

Although you can make sscanf work, this solution is more appropriate for C programs. In C++ you should prefer string stream:

string s("{10}{20}Hello World!"); stringstream iss(s); 

Now you can use the familiar stream operations for reading input into integers and strings:

string a; int x, y; iss.ignore(1, '{'); iss >> x; iss.ignore(1, '}'); iss.ignore(1, '{'); iss >> y; iss.ignore(1, '}'); getline(iss, a); 

Demo.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! :) Exactly what I was looking for!
3

You could use the method String.find() to get the positions of '{' and '}' and then extract the data you want through String.substr().

Comments

1

Solution using Regular Expressions:

#include <iostream> #include <regex> std::string line = "{10}{20}Hello World!"; // Regular expression, that contains 3 match groups: int, int, and anything std::regex matcher("\\{(\\d+)\\}\\{(\\d+)\\}(.+)"); std::smatch match; if (!std::regex_search(line, match, matcher)) { throw std::runtime_error("Failed to match expected format."); } int start = std::stoi(match[1]); int end = std::stoi(match[2]); std::string text = match[3]; 

Comments

-2

text does not need to have an "&" in front of it inside the sscanf, since string names are already pointers to their starting address.

sscanf(line, "{%d}{%d}%s", &start, &end, text); 

2 Comments

I get: warning: format specifies type 'char *' but the argument has type 'string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') [-Wformat]
@RajeevSingh My bad. I have edited the question without notice. It is still relevant :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.