0

I am using the command line to get input of 3 floats separated by spaces. e.g. "1.234 5.678 9.012".

I am currently using:

float xyz[3] = {0}; scanf("%f", xyz); print(%f %f %f, xyz[0], xyz[1], xyz[2]); 

However the output is "1.234000 0.000000 0.000000".

Expected output is "1.234000 5.678000 9.012000"

EDIT: I need to use floats instead of integers.

8
  • What were you expecting? Commented Oct 29, 2014 at 5:31
  • @Roecrew see my edit above Commented Oct 29, 2014 at 5:32
  • 1
    What is scant? Do you mean scanf? Commented Oct 29, 2014 at 5:36
  • Yeah. Autocorrect... Commented Oct 29, 2014 at 5:36
  • 2
    you are scanning a single float and printing 3 floats. try looping the scanf() thrice and look for the result Commented Oct 29, 2014 at 5:51

2 Answers 2

2

Maybe this

#include <stdio.h> int main(int argc, char** argv) { float vals[3]; printf("input 3 float values: "); int res = scanf("%f %f %f", &vals[0], &vals[1], &vals[2]); if(res == 3) { printf("read 3 floats %f %f %f\n", vals[0], vals[1], vals[2]); } else { printf("failed to read 3 float values\n"); } return 0; } 
Sign up to request clarification or add additional context in comments.

1 Comment

this line: if(res >= 0) fails to assure that 3 items were read. The line should be: if(res == 3)
2

If you use command line arguments , simply try like

#include<stdio.h> #include<stdlib.h> main(int c, char **v) { float xyz[3]={0}; xyz[0]=atof(v[1]); xyz[1]=atof(v[2]); xyz[2]=atof(v[3]); printf("%f %f %f\n",xyz[0],xyz[1],xyz[2]); } 

2 Comments

this is correct for what the OP stated they were actually doing.
This should check that c (conventionally argc) is at least 3 before proceeding with the atof calls, if its less than 3 segfault. @user3629249 I disagree that this is more in line with what the OP stated they were actually doing, they said they were using scanf.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.