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.

Recommended Answers

All 2 Replies

I think it's just the X in your input file (should be a 1 maybe?). Your expected output is unexpectedly short, having only nine members.

Why not try the easy way to read files?

ifstream fin(Filename.c_str());

	if(fin == NULL)
		cout << "Cannot open file." << endl;

	vector<string> Lines;
	string line;
	
	while(getline(fin, line))
	{
		Lines.push_back(line);
	}
	
cout << "NumLines: " << Lines.size() << endl;

	for(unsigned int i = 0; i < Lines.size(); i++)
		cout << Lines[i] << endl;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.