I have a following problem. I want to convert a string like "10 15 30"
to an int array with ints 10, 15, 30
. I searched in google a lot, but usually solutions included vectors (which I am not familiar with) or other more complex solutions. I found a code like this:
#include <cstdio>
void foo ( char *line ) {
int num, i = 0, len;
while ( sscanf( line, "%d%n", &num, &len) == 1 ) {
printf( "Number %d is %d; ", i, num );
line += len;
i++;
}
}
int main ( ) {
char test[] = "12 45 6 23 100";
foo( test );
return 0;
}
It works and extracts numbers from string in a way I wanted, but I don't understand part with:
line += len;
Can someone explain how it works? Why are we adding len
(which is int
) to the string?
Solution for C++:
#include <iostream>
#include <sstream>
#include <vector>
std::vector< int > foo ( char *c_str ) {
std::istringstream line( c_str );
std::vector< int > numbers;
for ( int n; line >> n; )
numbers.push_back( n );
return numbers;
}
int main ( ) {
char test[] = "12 45 6 23 100";
std::vector< int > numbers = foo( test );
for ( int n : numbers )
std::cout << n << ' ';
return 0;
}
Output:
12 45 6 23 100
%n
specifies the number of characters accessed by sscanf
in its one execution and saved it in variable len. so line + =len;
is incrementing variable line
, with number of characters accessed by sscanf
line + =len;
is nothing but line =line+ len;
line += len;
is equivalent to line = line + len;
line
is a char pointer, thus the code increases the pointer by len
, so that the pointer points to the next number, every time the loop is executed. Note than len
is updated by the call to sscanf()
.
The "string" is a pointer to a character buffer. You are performing pointer arithmetic to increment the sscanf to parse the next int characters from the buffer. So, in your example:
char test[] = "12 45 6 23 100";
say *line points to test, and has some pointer value, we don't care what the value is per-se, so let's say it is 1000. After the 1st call to sscanf, you read "12" in. That is two characters, so len should return 2. line then gets set to 1002, and is now "pointing" to the next set of characters in the buffer. sscanf reads that, and this continues until no more characters in the buffer.
Look at sscanf docs . It receive format and additional params.
In params you have "%d%n"
which you explain using format table from docs .
d or u
Decimal integer
Any number of decimal digits (0-9), optionally preceded by a sign (+ or -). d is for a signed argument, and u for an unsigned.
n
Count
No input is consumed. The number of characters read so far from stdin is stored in the pointed location.
So you read integer from string and number of chars this integer consist from.
After reading part of string you move pointer into number of read chars.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.