195k views
4 votes
how can i collect 1 2 10 3 4 into int array in c? i mean there is a '\t' between each int and i dont want to turn a string array into int which will cause stack overflow

1 Answer

6 votes

Final answer:

To collect numbers separated by tabs into an int array in C, you can utilize functions like sscanf or strtol and a loop to parse and store the numbers. Ensure the int array is sufficiently sized and include error checks for safe conversions.

Step-by-step explanation:

To collect numbers separated by a tab character ('\t') into an int array in C, you can use a function like sscanf or strtol in combination with a loop to process each number individually. First, you'll need to set up a char array (string) to hold your input, and then use a loop to parse each number and store it into your int array. It's important to check each conversion for success to avoid possible errors.

Here's a simple example:

#include
#include

int main() {
char input[] = "1\t2\t10\t3\t4";
int numbers[5];
char *ptr = input;
int index = 0;

while (index < 5) {
int num;
char *next_ptr;
num = (int)strtol(ptr, &next_ptr, 10);
if (ptr == next_ptr) {
break; // No more numbers
}
numbers[index++] = num;
ptr = next_ptr;
if (*ptr == '\t') {
ptr++; // Skip the tab character
}
}

// Now numbers[] contains the integers 1, 2, 10, 3, 4
for (int i = 0; i < index; i++) {
printf("%d\\", numbers[i]);
}

return 0;
}

Make sure that the array size is large enough to hold all expected integers to avoid stack overflow or other memory-related issues.

User Aleksander Ikleiw
by
8.0k points