-5

I have a char variable such as a = ' 123' or b = '\t123'. So how to convert them into integer? My problem is read form text file contains multi lines of char like a and b. I want to convert them and save to an array. Here is my code:

int main(){
FILE *file_pid;
int i = 0;
int number[100];
char line[20];
    file_pid = fopen("pid.txt","r");
    while(fgets(line, sizeof line, file_pid) != NULL){
         number[i] = atoi(line);
         i++;
    } 
}

Edited: I solved my problem. Many thanks!

DT_NoHope
  • 47
  • 1
  • 11

1 Answers1

0

you can use atoi() function to directly convert a string into integer. The C library function:

int atoi(const char *str) converts the string argument str to an integer. This function returns the converted integral number as an int value. If no valid conversion could be performed, it returns zero. good part is that it ignores spaces.

you might not want to store multi-character character constant in a character variable. Use character array instead example:

char c[] = " 123"; printf("%d\n", atoi(c));

coco97
  • 65
  • 7