I am new to C and I am confused how I can read through a file and store each line to an index of an array.
Example file:
What color is the sky?
Red
Orange
Yellow
Blue
Desired result of code:
input[0] = What color is the sky?
input[1] = Red
input[2] = Orange
input[3] = Yellow
input[4] = Blue
Hhere is what I have so far:
char input[60];
//declare string array of size 80, for 80 lines
for(int i = 0; fgets(input, sizeof(input), inFile)!=NULL; i++){
//string[i] = input; storing this line to the string index
}
//later on use the string[80] that now has all lines
I understand that declaring input[60] is only determining the length of each line, not the number of lines. I am so used to thinking about strings in other coding languages, that the use of char is throwing me off. I have tried video tutorials but they didn't help me.
stringan array of arrays of characters, and usestrcpy?malloc()et al? If so, you could use that to make copies of the strings (lines) you read. If you've not coveredmalloc()andfree()yet, then use the simpler but less flexible 2D array of characters. Don't forget to remove the newline thatfgets()includes in the data. (Since you've got a comment about a string array of size 80 for 80 lines, what do you plan to write there? Why didn't you write it?)char array[80][70];would allow you to store up to 80 lines of up to 70 characters each, where the character count includes the terminating null byte (so up to 69 displayable characters and one null byte at the end). It's not obvious whystrcpy(array[i], input)would crash your program unless you get more than 80 input lines. You should check that you don't go beyond the end of your array (thatidoes not reach or exceed 80). Please read about creating an MCVE (minimal reproducible example). That helps us to help you better.