I have following data in a file:
Name
Surname
#include <stdio.h>
#define FILENAME "file.txt"
#define MAXSIZE 128
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
FILE *file = fopen(FILENAME, "r");
if (!file) {
perror(FILENAME);
return 1;
}
int ch;
size_t i = 0;
char array[3][MAXSIZE];
for(int a=0; a < 3; a++)
{
while (i < MAXSIZE - 1 && ((ch = getc(file)) != EOF))
{
if (ch == '\n')
break;
array[a][i++] = ch;
}
/* null-terminate the array to create a string */
array[a][i] = '\0';
}
fclose(file);
for(int a=0; a < 3; a++)
{
for(int i=0; i < 10; i++)
{
printf("%c", array[a][i]);
}
}
}
When I run this program it gives me output like this
"
How can I modify it, so it will not output garbage?
This is a link to my previous post:
Link
>Solution :
As I noted in a comment:
Your printing loop
for (int i=0; i < 10; i++) { printf("%c", array[a][i]); }needs to stop whenarray[a][i] == '\0'—— addif (array[a][i] == '\0') break;before theprintf().You also need to reset
ito 0 before the while loop (but after theforloop). If you declarediinside the first for loop, you’d not have the problems you do.
Note that you have two different variables called i (one is size_t i = 0; before the loops; the other is for (int i = 0; …) while printing) and one hides the other. That can lead to confusion.
Those changes might lead to this code:
#include <stdio.h>
#define FILENAME "file.txt"
#define MAXSIZE 128
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
FILE *file = fopen(FILENAME, "r");
if (!file) {
perror(FILENAME);
return 1;
}
char array[3][MAXSIZE];
for (int a = 0; a < 3; a++)
{
int ch;
size_t i = 0;
while (i < MAXSIZE - 1 && ((ch = getc(file)) != EOF))
{
if (ch == '\n')
break;
array[a][i++] = ch;
}
array[a][i] = '\0';
}
fclose(file);
for (int a = 0; a < 3; a++)
{
for (int i = 0; i < 10; i++)
{
if (array[a][i] == '\0')
break;
printf("%c", array[a][i]);
}
}
}
There’s also no obvious reason not to print the data using:
for (int a = 0; a < 3; a++)
puts(array[a]);
or
for (int a = 0; a < 3; a++)
printf("%s\n", array[a]);