简体   繁体   中英

Best Way to Convert Array of Strings to Array of Int in C

My current problem is to read in an unknown number of integers from stdin . My approach is to use gets() to store the entire line as a char array ( char str[50] ). I am trying to parse the char array and convert each "string int" to an integer and store in an int array. I tried using strtol ( nums[i]=strtol(A, &endptr, 10) where A is the char array. However, endptr doesnt seem to store anything when the rest of the A are also numbers. For example, if A is "8 hello" endptr=hello, but when A is "8 6 4" endptr is nothing.

Is there a better approach? Is this possible with atoi ? Any help is greatly appreciated! Thanks!

char A[1000];
long nums[1000];
printf("Enter integers: ");
gets(A);
char *endptr;
int i=0;
while(endptr!=A){
    nums[i]=strtol(A, &endptr, 10);
    i++;
}

This should extract the (positive) integers and skip right over anything else that's not an integer:

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

char string[1024];
long numbers[512]; // worst case ~ 1/2 number of chars = "1 1 1 1 1 1 ... 1"

/* ... */

printf("Enter integers: ");
fgets(string, sizeof(string), stdin);

char *endptr, *ptr = string
int count = 0;

while (*ptr != '\0') {
    if (isdigit(*ptr)) {
        numbers[count++] = strtol(ptr, &endptr, 10);
    } else {
        endptr = ptr + 1;
    }

    ptr = endptr;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM