简体   繁体   中英

Place ints from text file into an int array in C

I am reading in a text file with content:

2, 0, 15, 14, 24, 6, 19, 9, 25, 13, 7, 5, 21, 10, 12, 11, 4, 22, 23, 20, 17, 8, 18, 3, 1, 16

I would like to put each individual elements into an int array and then print the array. My code below is giving me a segmentation fault but I cannot fix the issue. Any help would be great.

FILE *the_cipher_file;
the_cipher_file = fopen("cipher.txt", "r");
int * the_alphabet_array;
int size_of_alphabet;
int the_letter_counter = 0;

while(fscanf(the_cipher_file, "%d", &size_of_alphabet) > 0){
    the_alphabet_array[the_letter_counter] = size_of_alphabet;
    the_letter_counter++;
    printf("%d", size_of_alphabet);
}

Here is a simple program I wrote sometime back, its crude but should be what your looking for, also note to check the *fp for null.

I tested your data worked fine(read only the numbers and skip whitespace and comma).

2, 0, 15, 14, 24, 6, 19, 9, 25, 13, 7, 5, 21, 10, 12, 11, 4, 22, 23, 20, 17, 8, 18, 3, 1, 16    

#include <stdio.h>
int main(int argc, char *argv[]){

FILE *fp = fopen(argv[1],"r");
int array[100];
int size_of_alphabet =0;
int i =0;
while (fscanf(fp," %d%*[,] ",&size_of_alphabet)>0 && i<100) {
    array[i] = size_of_alphabet;
    printf("%d\n", size_of_alphabet);
    i++;

}
}

The input is the argv[1], so run the program with ./a.out file_name.txt

The * says throw away what is read, don't store it in an output variable, so in this case it will throw away the comma, the details of the [ can be found in the scanf or fscanf manual. most of the functions that end with an 'f'(printing formatted stuff), like scanf and fscanf have similar man pages.

using scanf and skipp stuff - http://classes.soe.ucsc.edu/cmps012a/Fall98/faq/scanfQ.html

fsacnf man page http://www.manpagez.com/man/3/fscanf/

Useful Information on the scanning functions.(beware of buffer overflows)

scanf("%[^,]",array); // it expects characters(string) that don't contain commas,
                      // commas will be skipped. 

Reading only a comma would like this

scanf("%[,]",array); only commas will be read as a string

Skipping a comma would look like below.

scanf("%d%*[,]",array); this one skips the comma if its after the number.

First of all test if fopen succeeded, that is if the_cipher_file != NULL .

Then make sure to handle commas - scanning the input file with "%d" format specifier reads and converts a sequence of digits as an integer value, but the separator remains unread in the input buffer. You need to skip it before the next loop iteration applies "%d" conversion again...

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