0

i tried converting integer into string using sprintf , but its giving me an error

here is my source code : #include "stdafx.h" #include <stdio.h> #include <stdlib.h> int i,a,b,c; char d[12]; char e[12]; int main(int argc, char const *argv[]) { for (i = 0; i < 1000 ; i++) { if (i<9) { printf("\n"); } if (i > 10 && i>=99) { sprintf (i,"%d",d); b = d[0]*d[0]*d[0] + d[1]*d[1]*d[1]; if (b==i) { printf("%d",i); } } else { sprintf (i,"%d",d); b = d[0]*d[0]*d[0] + d[1]*d[1]*d[1] + d[2]*d[2]*d[2]; if (b==i) { printf("%d",i); } } } return 0; }

3rd Sep 2017, 6:26 PM
Hridyansh Thakur
Hridyansh Thakur - avatar
2 Réponses
+ 2
You're using sprintf() incorrectly: int sprintf ( char * str, const char * format, ... ); note the 1st parameter is a char pointer and you are passing an int. http://www.cplusplus.com/reference/cstdio/sprintf/ https://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Standard_C_Library/Functions/sprintf You're also trying to use d and b before they are initialized. if (b==i) b has not been set here
3rd Sep 2017, 7:18 PM
ChaoticDawg
ChaoticDawg - avatar
0
First : stdafx.h might not work on SoloLearn Second : If you can avoid using global variables, avoid ! You should declare your variables in the scope of the function that use them (here, in main) Third : switch i and d in all your sprintf calls Fourth : '0' > 0, if you want to get a figure from char to int, you need to do something like d[0] - '0' Fifth : you do not use stdlib.h functions and macros Sixth : you should remove c++ tag as it is clearly C I hope I helped you :) If you have any other question, please ask, I would be glad to answer ! PS : Points 2, 5 and 6 are more like something you should change than real errors. Point 4 is a logical error, not a syntax error. Point 1 might be useless if you compile this program on your computer and have this header file in the same directory, but I do not see functions that could be in it so it looks like it is useless
3rd Sep 2017, 7:39 PM
Baptiste E. Prunier
Baptiste E. Prunier - avatar