Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting multiple variables from a read in line

I am having trouble getting multiple number vars from a read in line. For a single value I can do strtol(), but how can I get the float and long values of a sentence that is similar to as follows.

Please aim 3.567 degrees at a height of 5 meters.

I tried doing two different calls to my buffer sentence, however it got neither of my values. I have no issues with get single values, but with to, I get 0.000 from my strtof call and 0 from mmy strtol call.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

ASSUMING YOU KNOW IN WHICH ORDER THE VALUES WILL BE IN

Here is an example of how you can get multiple numeric values from a string:

#include <stdio.h>
#include <stdlib.h>

int main() {
  // The string to parse
  char *str = "Please aim 3.567 degrees at a height of 5 meters.";

  // Variables to store the values
  float degrees;
  int height;

  // Parse the string and store the values in the variables
  // you can use sscanf, fscanf, scanf
  sscanf(str, "Please aim %f degrees at a height of %d meters.", &degrees, &height);

  // Print the values
  printf("degrees: %f\n", degrees);
  printf("height: %d\n", height);

  return 0;
}

In this code, the sscanf() function is used to parse the string and extract the values of the degrees and height variables. The sscanf() function takes the string to parse as the first argument, and a format string containing the conversion specifiers for the values to extract as the second argument. The & operator is used to pass the addresses of the degrees and height variables, so that the sscanf() function can store the extracted values in those variables.

After calling the sscanf() function, the degrees and height variables are printed to the console to verify that the values were extracted correctly.

-chatgpt

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading