parsing a formatted string

using the format library in C++20, and having done this:

1
2
int val = 25;
string str = std::format( "{0:2}", val);



How can we get the val from str, something like this:
1
2
3
int v = std::parse(str);
// or:
int v = std::parse(str, "{0:2}");


where parse does not exist as far as I know


Regards,
Juan
Last edited on
There isn't anything like std::format for parsing text input but there is a proposal:
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1729r1.html

In the meantime I recommend using std::istringstream.
I have this:


1
2
3
4
std::istringstream is{"5,600"};
is.imbue(std::locale{"en_US"});
double dou;
is >> dou;


it works but what if it had a currency symbol?

1
2
3
4
std::istringstream is{"$5,600"};
is.imbue(std::locale{"en_US"});
double dou;
is >> dou;



it does not work! dou no longer gets its value to 5600.00000 instead it has value 0.0000000


Last edited on
Pass the string as argument to the constructor and read from it the same way as you would from std::cin.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>

int main ()
{
	std::istringstream iss("hello 123");
	
	std::string word;
	iss >> word;
	
	int num;
	iss >> num;
	
	std::cout << num << " " << word << "\n"; // prints "123 hello"
}
There is sscanf() which works with null-terminated strings. See (3) of:
https://en.cppreference.com/w/c/io/fscanf

Consider:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <format>
#include <string>
#include <cstdio>

int main() {
	const int val { 25 };
	const auto str { std::format("{0:2}", val) };

	std::cout << str << '\n';

	int val1 {};

	std::sscanf(str.c_str(), "%i", &val1);

	std::cout << val1 << '\n';
}



To just obtain a number from std::string, there are the stoxxx functions. See https://cplusplus.com/reference/string/

However these (and from_chars() ) just convert one value. They're not really the opposite of std::format() which can deal with multiple values. Until std:parse() comes, the nearest is sscanf().
Topic archived. No new replies allowed.