following are the strings provided by the user to me -
"1 20";
"1 203";
"1 2030";
in above examples 1 is query and 20,203,2030 are the numbers to be extracted,how can I extract them in C language?
CodePudding user response:
There are many ways to parse a string containing numbers. If you expect the string to have a fixed format with 2 integers, the simplest solution is to use sscanf():
#include <stdio.h>
int parse2numbers(const char *str) {
int a, b;
// sscanf returns the number of successful conversions
int n = sscanf(str, "%d%d", &a, &b);
if (n == 2) {
printf("success: a=%d, b=%d\n", a, b);
return 1;
}
if (n == 1) {
printf("failure: only one number provided: a=%d, str=%s\n", a, str);
return 0;
}
if (n == 0) {
printf("failure: invalid format: %s\n", str);
return 1;
}
printf("failure: encoding error: n=%d, str=%s\n", n, str);
return 0;
}
If the string can contain a variable number of integers, you could use strtol() to parse one integer at a time:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
void parse_numbers(const char *str) {
long a;
char *p;
for (;; str = p) {
errno = 0;
// strtol returns a long int
// updates `p` to point after the number in the source string
// sets errno in case of overflow and returns the closest long int
a = strtol(str, &p, 10);
if (p == str)
break;
if (errno != 0) {
printf("overflow detected: ");
}
printf("got %ld\n", a);
}
if (*str) {
printf("extra characters: |%s|\n", str);
}
}
CodePudding user response:
I have not tested it but I think theoratically this should work
int rows=2, columns=4 // defining length of array
char ch[rows] [columns] = {"1 90"}, {"2 90"}; // creating two dimentional array for sample data
for (int i = 0; i < rows; i ) { // looping throw first dimention
// this only works if data is sorted and there is no missing indes in between like [1 200] [3 200] will not work but [1 200] [2 200] should
char* index;
if ( ch[i] [0] != itoa(i 1, index, 10) ) // checking if index donot match the row then skip this itteration and move to next one.
continue;
for ( int j = i 2; j<columns; j ) { // looping through second dimention
printf("%c\n", ch[i][j]); // printing that second dimention
}
}
