Hi,
I am trying to read number from file. Following is my code.
I am not able to read it correctly. When i>1 then i should read the second and third line of the file and store the values in the vector rows. But it is not reading the second and third line.
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
int main()
{
FILE *file; /* declare a file pointer */
char c;
int *var;
int i=0;
int count = 5;
int lines = 0,num;
var = new int[count];
int junk = 0;
std::vector<int> rows;
file = fopen("hello1.txt","r");
if(file == NULL)
{
printf("Error : cannot open file. \n");
exit(1);
}
else
{
fscanf(file, "%d", &lines); // number of lines
for(int i=1; i<=lines; i++)
{
if(i==1)
{
for(int j=0; j<count; j++)
{
fscanf(file, "%d", &var[j]);
}
}
else
{
for(int j=0; j<count; j++)
{
fscanf(file, "%d", &num);
if(num==1)
{
rows.push_back(-1*var[j]);
}
if(num==0)
{
rows.push_back(var[j]);
}
}
}
}
}
fclose(file);
for(int j=0; j<rows.size(); j++)
{
printf("%d ", rows[j]);
}
return 0;
}
Input file : hello1.txt is as follows:
3
1 12 3 10 14
1 X 0 0 1
0 1 1 0 0
Output obtained is as follows
-1 -12 -3 -10 -14 -1 -12 -3 -10 -14
Expected output:
-1 3 10 -14 1 -12 -3 10 14
I am unable to figure out why fscanf is not reading. Any help would be great.
Thanks.