I have a string (char) and I want to extract numbers from it.
So, I have a line: 1 2 3 4 /0And now I need variables, so I can use them as an integer:a=1, a=2, a=3, a=4
1 2 3 4 /0
a=1, a=2, a=3, a=4
How can i do this?
If the line always contains 4 numbers, separated by spaces, then this can be done using sscanf:
sscanf(string, "%d %d %d %d", &a, &b, &c, &d);
If the number of numbers changes, you need to parse the string.
Please clarify your question.
, , , , . sscanf, , . sscanf , 4.
if (4 != sscanf(buf, "%d %d %d %d", &a, &b, &c, &d)) { /* deal with error */ }
buf "1 2 3" "1 2 a b" - , sscanf .
As others have noted, if you know how many numbers to expect, sscanf is the easiest solution. Otherwise, the following sketches have a more general solution:
First mark the line with spaces. The standard C method for this strtok () is :
char* copy; char* token; copy = strdup(string); /* strtok modifies the string, so we need a copy */ token = strtok(copy, " "); while(token!=NULL){ /* token now points to one number. token = strtok(copy, " "); }
Then convert the string to integers. atoi () will do this.
sscanf () can do this.
#include <stdio.h> int main(void) { int a, b, c, d; sscanf("1 2 3 4", "%d %d %d %d", &a, &b, &c, &d); printf("%d,%d,%d,%d\n", a, b, c, d); }
Source: https://habr.com/ru/post/1698564/More articles:Double throw for Double is less than zero - javaУстановка AssociatedControlID на метку не выполняется - asp.nethttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1698561/how-can-i-programmatically-add-playlists-or-views-to-itunes&usg=ALkJrhibeC_eDWhLtFDNQtSGr0OpNfNIhAКак вставить Ruby в движок XNA? - rubyRuby Daemons не запускается - rubyHow to define a font as symbolic in java? - javaHow can you determine the MySite user id - c #Is it better to write a more focused stored procedure with fewer parameters? - sqlHow to specify in Eclipse what to include in a .WAR file - javahttps://translate.googleusercontent.com/translate_c?depth=1&pto=aue&rurl=translate.google.com&sl=ru&sp=nmt4&tl=en&u=https://fooobar.com/questions/1698569/protecting-user-passwords-in-desktop-applications&usg=ALkJrhjlr2cPRTWREiHJI9QfXWEWrZ1h2AAll Articles