Reputation: 1243
I already know how to compare char type with newline (\n) but I would like to know how to compare an Integer with the newline (\n). Is it possible? (I did researches to find my answer but I end up getting answer that require char types)
I've the text file input with numbers:
11 22 33 44 55 1
2 3 4 56 777
1
255
3
5
I want the output to look like this
[11][22][33][44][55][1]<newline>[2][3][4][56][777]<newline>[1]<newline>[255]<newline>[3]<newline>[5]<newline>
lineNumber:[6]
but the output I get is
[11][22][33][44][55][1][2][3][4][56][777][1][255][3][5]
lineNumber:[0]
This is the code I'm using
int *integers = malloc(sizeof(int) * 200);
int i=0, lineNumber=0, num=0;
//int num;
while(fscanf(file, "%d", &num) > 0)
{
if(num == '\n'){
printf("<newline>");
lineNumber++;
}
integers[i] = num;
printf("[%d]", integers[i]); // Just to show output.
i++;
}
printf("\nlineNumber:[%d]", lineNumber);
Reason why I don't want to use the char type is because I've to re-convert the char digits into integer... I would like to care about the newline (\n) and integers only
Upvotes: 0
Views: 3130
Reputation: 97717
You can attempt to read a newline character after each integer then check the return of fscanf to see how many items were read.
int *integers = malloc(sizeof(int) * 200);
int i=0, lineNumber=0, num=0;
int read;
char nl[2];
while((read=fscanf(file, "%d%[\n]", &num, &nl)) > 0)
{
integers[i] = num;
printf("[%d]", integers[i]); // Just to show output.
i++;
if(read == 2){
printf("<newline>");
lineNumber++;
}
}
printf("\nlineNumber:[%d]", lineNumber);
Upvotes: 1