Hey so Im currently trying to store multiple strings that are coming from a text file from the command line args. I have been told to use a 2D array so i declared one of size [count] which is 4 in this example. However when i got to use fgets to store each line in the array, it doesnt seem to be working as when i print the result to console, i get a bunch of random characters.
count = 4;
char string_array[count][100];
int loop_counter = 0;
while (!feof(file_pointer) && loop_counter < 10)
{
fgets(string_array[loop_counter], 150, file_pointer);
loop_counter += 1;
}
printf("First string is %s", string_array[0]);
The last printf statement returns this:
First string is ▒▒ap▒ X▒a
See the random characters^. First string is supposed to be "A 1 2 3 4 5". The text file looks like this:
A 1 2 3 4 5
B 0 0
C 1 1
F 2 2
As @kleshenki mentioned, it could be an encoding issue.
I tried refactoring the code to use getline instead. So give that a go. If it doesn't work, I will delete this post.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int count = 4;
char string_array[count][100];
FILE *fp = fopen("test.txt","r");
ssize_t read;
int i = 0;
size_t n = 100;
char *lines = string_array[i];
while (i<count&&( read=getline(&lines, &n, fp) )!= -1)
{
lines = string_array[i];
}
printf("First string is %s", string_array[0]);
printf("Second string is %s", string_array[1]);
fclose(fp);
}
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.