Hi I'm trying to convert elements of an array into integers using input from the user.
#include <stdio.h>
#include <string.h>
int main()
{
char i[9]={'-','-','-','-','-','-','-','-','\0'};
int j;
printf ("enter an integer for an element ");
sscanf(i, "%d", &j);
return 0;
}
I read somewhere that using sscanf is one way to do it but I don't know the correct way to use it.
scanf
reads from the standard input.
sscanf
reads from a string.
Example of scanf
usage:
#include <stdio.h>
int main()
{
char str1[20];
printf("Enter name: ");
scanf("%s", str1);
printf("First char converted to int: %d\n", str1[0]);
int j = str1[1];
printf("Second char converted to int: %d\n", j);
return(0);
}
Input and Output:
Enter name: marcel
First char converted to int: 109
Second char converted to int: 97
As Marcel said, there are two different functions that do different things. You request convert elements of an array into integers using input from the user , so I can think you want this:
char i[9]={'-','-','-','-','-','-','-','-','\0'};
int j;
printf ("enter an integer for an element ");
scanf("%i", &j);
printf("Element[ %i ] in integer is: %i", j, i[j]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.