Reputation: 64
I am fairly new to the world of programming so please forgive me if this is a common mistake.
I'm trying to scan 3 double values and 3 strings out of one input string but it doesnt continue after the second value.
double total_weight_kg(char *s, int Length) {
double weights[3];
char units[3];
int test = sscanf(s, "%lf, %s, %lf, %s, %lf, %s",
&weights[0], &units[0],
&weights[1], &units[1],
&weights[2], &units[2]);
printf("%i\n", test);
printf("%s\n", &units[0]);
int main(void) {
total_weight_kg("5, g, 1, t, 175, kg", 3);
return 0;
The first print prints out 2 and the second the g.
Furthermore I'd like to compare units[i] in a loop but can't seem to get that working either.
for (int i = 0; i < Length; i++) {
w = weights[i];
if (strcmp(units[i], "kg") == 0) {
weight += w;
}
}
I hope you can help me find a solution for this problem,
edit: Everyting is working as intended now. Thank you very much for your help. ( 19[^,] was one major problem )
Upvotes: 3
Views: 1637
Reputation: 144740
There are some problems in your code:
To scan the strings into units
, you must define it as a 2D array of char
:
char units[3][20];
You should modify the scanf
format to stop the word parsing on ,
and spaces, as suggested by user3386109.
Also modify the printf
to pass the array instead of its address.
Here is the modified code:
double total_weight_kg(char *s, int Length) {
double weights[3];
char units[3][20];
int test = sscanf(s, "%lf, %19[^, \n], %lf, %19[^, \n], %lf, %19[^, \n]",
&weights[0], units[0],
&weights[1], units[1],
&weights[2], units[2]);
printf("%i\n", test);
printf("%s\n", units[0]);
...
}
int main(void) {
total_weight_kg("5, g, 1, t, 175, kg", 3);
return 0;
}
Upvotes: 2