Trying to copy "0.75" as a double from argv[] [closed] - c

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Improve this question
For some reason anything I try results in numbers after the decimal place being disregarded.
sscanf(argv[5], "%.2lf", &add4); doesn't work
add4 = atof(argv[5]); doesn't work
Any help?
1: program name (aka for the program im trying to solve currently, i need the following parameters. of these, double isnt getting saved properly)
2: string
3: int
4: int
5: double
all but the double are being copied into my arrays fine. I've tried the above two ways of copying the double but both result in numbers after the decimal being .00
Declarations:
char add1[50];
int add2, add3;
double add4;
This call adds a new line to a list .csv file:
inv add banana 2 2 2.50
where below, command has already been assigned the string "add".
what would end up listed would be:
"banana, 2, 2, 2.00" at the end of my text file
if(strcmp(command,"add") == 0)
{
strcpy(add1, argv[2]);
add2 = atoi(argv[3]);
add3 = atoi(argv[4]);
add4 = atof(argv[5]);
FILE *fp3 = fopen("replica.csv", "w");
for(j=0;j<i;j++)
{
fprintf (fp3, "%s,%d,%d,%.2lf\n", item[j], quantity[j], limit[j], cost[j]);
}
fprintf(fp3, "%s,%d,%d,%.2lf\n", add1, add2, add3, add4);
fclose(fp1);
fclose(fp3);
remove("inventory.csv");
rename("replica.csv", "inventory.csv");
}

Enable more warnings and check the return value of sscanf.
% clang test.c
test.c:5:28: warning: invalid conversion specifier '.' [-Wformat-invalid-specifier]
int n = sscanf(argv[1], "%.2lf", &x);
~^
1 warning generated.
atof works for me. Make sure you're including stdlib. You could also try stdtod(argv[5], NULL).

Try:
sscanf(argv[5], "%lf", &add4);

Related

Variable in C not printing the given value [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Alright, so basically recently I started studying C as a hobby, and I wanted to create a small program.Everything works fine, but when I make the variable "Age" like this:
int myAge = "14";
printf("My age is%d\n", myAge);
It prints out 1642.
I have tried switching to
printf('My age is%i\n', age);
But it did the same.
I also tested changing the number to a string but it obviously failed, because this isn't Python.
Anybody can help?
Save time, enable all compiler warnings.
Perhaps receive a warning like:
warning: initialization of 'int' from 'char *' makes integer from pointer without a cast [-Wint-conversion]
int myAge = "14"; sets myAge to the address of the string literal "14".
Instead, initialize with an int.
int myAge = 14;
This is a fixed version of your program. Just declaring the age variable as an integer is enough to fix it.
#include <stdio.h>
int main() {
int age = 14;
printf("My age is %d", age);
}
Friendly note:
C is not like Python. Arrays don't work the same, strings don't exist, and programming in C is fundamentally different in every way. I would advise that you definitely take a course rather than trying to teach yourself from scratch.
u should write int myAge = 14 , writting 14 in double quotes means its a string (thx HAL)
We use double quotes when we have string and single quote when we have character but 14 is an integer we should write int myAge=14; or if u want "14" u should write char myAge[2]="14"; then printf("%s",myAge);

Extracting Numbers from String in C [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have an ASCII string coming from UART that looks something like "43.533a,5532" and I'd like to extract the two numbers. My idea was to separate them using strtok with the comma as delimiter and then remove the last character from the first string and afterwards convert the numbers using atoi() or is there an easier way with sscanf()? String manipulation is nothing I'm regularly using.
Another problem is, if the String looks different, how could I catch that beforehand?
Yes you can do this easily with sscanf().
Following is an example. See it working here:
#include <stdio.h>
int main(void) {
float a;
int b;
char *sNum = "43.533a,5532";
sscanf(sNum, "%fa,%d", &a, &b);
printf("a= %f || b= %d", a,b);
return 0;
}
Output:
a= 43.533001 || b= 5532
Note: Since float is having precision to 6 decimal place by default, so you may need to consider it and correct it if necessary.

no answer from simple subtraction code in C [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
i wrote code, and it gives me answers like 0.00 and 1.00, not actual math answer. Where i made mistake? (im begginer, dont scream on me :) )
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a,b;
float x;// score
// Request 1
printf("Zadanie 1(12)\n");
// Calculate the square root of the given interval
printf("Oblicz pierwiastek rownania w podanym przedziale\n");
// Give me a number a
printf("Podaj liczbe a:\n");
scanf("%d",&a);
// Give me a number b
printf("Podaj liczbe b:\n");
scanf("%d", &b);
x=&a-&b;
//answer
printf("%f", x);
system("PAUSE");
return 0;
}
x = a - b
not
x = &a - &b
Explanation: The & operator gives you the memory address of a, which you need to give to scanf, so that it can place data there. But you do math on the actual value of a.. which is just a.
because of pointer arithmetic:
x = &a - &b;
computes the distance between the addresses of a and b, which are probably close since they're auto variables of the same type declared close-by. My guess is that you could get 1 or -1 (or any other integer value but not 0 since a and b are located in 2 separate addresses) then put in a float.
(the difference of addresses of 2 consecutive integers is 1, independently of the size of the integer)
You need of course to do:
x = a - b;
You've been misled by the fact that scanf needs a pointer on a or b to be able to write a value when reading the input.

write values from multidimensional array to .csv-file [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am writing C-program that in the end will contain two large 2-dimensional arrays that I need to export to two csv.files.
The arrays (doubles) are 10000 rows long, and between 8 and 30 columns long, depending on what the user define, example below:
int NOS = 10000;
int Tau_length = 15;
Energy_system_Array[NOS][Tau_length];
I have created two file pointers:
FILE *fp1, *fp2;
At the end of the program, I have written these lines:
int array_rowit, array_colit;
fp1 = fopen("Energyarray.csv", "w");//create a file
if (fp1 == NULL)
{
printf("Error while opening the file.\n");
return 0;
}
for (array_colit = 0; array_colit<Tau_length; array_colit++){
for (array_rowit = 0; array_rowit< start_measure; array_rowit++){
fprintf(fp1, Energy_system_array[array_rowit,array_colit]);
fclose(fp1);
}
}
But when I compile the c-code, this is the message I get:
main.c: In function 'main':
main.c:413:22: error: incompatible type for argument 2 of 'fprintf'
fprintf(fp1, Energy_system_array[array_rowit,array_colit]);
^~~~~~~~~~~~~~~~~~~
In file included from main.c:1:0:
C:/MinGW/x86_64-w64-mingw32/include/stdio.h:378:15: note: expected 'const char * restrict' but argument is of type 'double'
int __cdecl fprintf(FILE * __restrict__ _File,const char * __restrict__ _Format,...);
^~~~~~~
I am a real novice when it comes to C-programing, so I hope someone can help me with this.I have searched around for different guides, but I haven't found any that describes my situation exactly.
I should mention that the csv files should be overwritten for each run of the program. It cannot save the values from an earlier run of the program.
To write the whole array as CSV, use:
for (array_colit = 0; array_colit<Tau_length; array_colit++){
for (array_rowit = 0; array_rowit< start_measure; array_rowit++){
fprintf(fp1, "%lf%s",Energy_system_array[array_rowit,array_colit],
(array_rowit<start_measure-1?",":""));
}
fprintf(fp1,"\n");
}
fclose(fp1);
Notes:
append a comma after each value but the last one
add a newline after every row
close the file only once everything has been written out.

How to write a datastructure to a file with fput in c? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
What i have here is a struct that i want to print to a file. The structure consists of a series of singel character ints where pek3 Points at the first object containing a number in the structure.
fprintf didnt work and this just gives me the error:
missing ')' Before '->'
FILE *filen;
int h;
talstrul *tepek = pek3;
filen = fopen("summadata.txt","w");
for(h=1; h<=maxlen; h++)
{ int fput(tepek->num,filen);
tepek = tepek->next;
}
fclose(filen);
Your example is incomplete - so we have to guess.
f = fopen("summadata.txt","w");
for(int h=1; h<=maxlen; h++) {
fprintf(f, "%d\n", tepek->num);
tepek = tepek->next;
}
fclose(f);
should work.
fprintf works as follows:
the first argument is the file handle, that is what you get from fopen.
the format string, here "%d\n", describes, what you want to print. Here it is a integer ("%d") and then a newline ("\n").
then comes the arguement(s) to the formatstring. In this case the integer, I guess that is tepek->num.

Resources