Home > front end >  How to convert char array to int?
How to convert char array to int?

Time:09-22

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  char str[10];
  int x, y, z;
  for(int i = 1; i <= strlen(str); i  ){
    str[i] = i;
  }

  sscanf(str, "%d", &x); // Using sscanf
  printf("\nThe value of x : %d", x);

  y = atoi(str); // Using atoi()
  printf("\nThe value of y : %d", y);

  return 0;
}

I tried using both sscanf and atoi, but neither of them seems to work. Any idea how to convert str to an int?

CodePudding user response:

This loop:

for(int i = 1; i <= strlen(str); i  ){
    str[i] = i;
}

is strange and wrong. If you were trying to use that loop to construct the string to convert, try this:

int i;
for(i = 0; i < 5; i  ) {
    str[i] = (i   1)   '0';
}
str[i] = '\0';

printf("The string: %s\n", str);

Here I've made several changes:

  1. The loop runs from 0 to 4, to set just the first 5 positions in str[]. (Your loop started at 1, which meant it failed to set str[0], and it tried to run until strlen(str), which can't work because str hasn't been set to anything, so you can't compute its length.)

  2. When storing values into str[i], it adds 1 to i (meaning it will set positions [0] to [4]), and then additionally adds in the constant '0' (which is 48 on an ASCII machine) to convert the numbers 1 — 5 to the digit characters '1' to '5'.

  3. After setting 5 digits, it sets str[i] = '\0'; to add proper null termination for the constructed string.

Then it prints out str so you can see what it is, before trying to convert it to an int using atoi and scanf.

CodePudding user response:

char myarray[] = "-123";
int i;
sscanf(myarray, "%d", &i);

will convert char array to int

  • Related