How can we convert String to corresponding primitive type?
- We collect the input in String format from command line.
- dos.h header file is providing functions for this data conversions.
- The two functions used for data conversions as follows
- int atoi(char* s) : Converts input string to integer on success
- float atof(char* s) : Converts input string to float on success
Program to display Arguments count:
#include<stdio.h> int main(int argc , char* argv[]) { printf(“Count is : %d \n”, argc); return 0; } |
cmd/> Program Output : Count is : 1 cmd/> Program 10 20 30 40 50 Output : Count is : 6 cmd/> Program 10 23.45 g online Output : Count is : 5 |
Program to display list of input arguments:
#include<stdio.h> int main(int argc , char* argv[]) { int i; if(arc==1){ printf(“No input values \n”); } else{ printf(“Arguments are :\n”); for(i=1 ; i<argc ; i++){ printf(“%s\n”, argv[i]); } } return 0; } |
cmd/> Program Output : No input values cmd/> Program 10 23.45 g online Arguments are : 10 23.45 g online |
Reading input from command line and add:
#include<stdio.h> int main(int argc , char* argv[]) { int i; if(arc<3){ printf(“Insufficient input values \n”); } else{ char* s1 = argv[1]); char* s2 = argv[2]); int x = atoi(s1); int y = atoi(s2); printf(“Sum is : %d \n” , x+y); } return 0; } |
cmd/> Program Output : Insufficient input values cmd/> Program 10 20 Output : Sum is : 30 |