Solved

Read fields

Posted on 2004-10-10
22
298 Views
Last Modified: 2010-04-01
Hi,

I am trying to read a file and store the fields in different arrays. I have tried using fgetc, fgetw but I am not able to separte the fields.

Eg:
Following is the file that i want to read

Name      Salary     ID
-------     --------    -----'
john        1000       1234
karen      2000        2345
Mary       3000        1112

I create a array of struc called data.

typedef struct data{
string name;
double salary;
int ID;
}data_obj;

then I create an array of this struct
data array[5];

I know how to open, close , read the file but can't figure out how to correctly store each of the field in the array.
Thank you.
0
Comment
Question by:icysmarty
  • 11
  • 9
  • 2
22 Comments
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
simply use fget(f,array[i], sizeof(data))
0
 
LVL 9

Expert Comment

by:jhshukla
Comment Utility
ifstream file("foo.dat");
data_obj Data[5];

for(int i=0;i<5;i++)
  file >> Data[i].name >> Data[i].salary >> Data[i].ID;

file.close();
0
 

Author Comment

by:icysmarty
Comment Utility
If I am using C programming, can I use fscanf?
Do you care to explain why declare data_obj Data[5].
This is how i read the file

FILE* input_file;
input_file = fopen("foo.dat", "r");
//check the error opening ..
  ...
 ...
...
call the function to read the data
0
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
if the are using FILE * there is 2 way to  open fopen("foo.dat", "r"); for text file or fopen("foo.dat", "rb"); for binary
if you using text file format then you can user fsacnf("%s%d%d",Data[i].name,Data[i].salary,Data[i].id)

provided that name contain no space

you can user data Data[5].


0
 

Author Comment

by:icysmarty
Comment Utility
Should fscanf takes the FILE* as parameter too? fscanf takes 3 parameters right?
All I get is zeros... so, I think the pointer of the file does not traverse through the data.

can I use fread to read how many rows of data do I have?
0
 
LVL 9

Expert Comment

by:jhshukla
Comment Utility
struct data array[5];
same as
data_obj Data[5];
just different variable name.

>> If I am using C programming, can I use fscanf?
sure.
fscanf(input_file, "%s %f %d ", array[i].name, &array[i].salary, &array[i].ID);
I used %f because I don't remember the format string for double. replace with appropriate code.

>> provided that name contain no space
Yeah. that's important!
If name can contain spaces then, try to read in a float. if it fails, append the string. retry until salary is successfully read. post a comment if help needed.

You asked the question in C++; so I replied in C++.
0
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
sorry i messed the file paramter as well as i messed & before the integers
0
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
if you made the application to write and read from the file then you can put the length of the string in 1st colmn so you can user fgets to return it agian with its size
0
 

Author Comment

by:icysmarty
Comment Utility
This is what I have... but it doesn't work ...
I have a question.
How does the pointer of the file traverse through the data?
From here, I see that fscanf is a reading a filed at a time... and how does it know what is theh next field?
Also, how to read end of the line?

int store_data(FILE *input_file){
      
                int count = 0;
      for ( i = 0; i< count; i++)
      {
      fscanf(input_file,"%s%f%d",array[i].name,array[i].salary,array[i].id);
                                count++;
            
      }

      return count;
}
0
 

Author Comment

by:icysmarty
Comment Utility
The function that I post above shows nothing when I run it...
This is because i think the pointer is not placed at the first byte of the input_file.
Can I use read?
0
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
of corese loop not work

while (! foef(input_file)  )
   {
     fscanf(input_file,"%s%f%d",array[i].name,array[i].salary,array[i].id);
                                count++;
         
     }

0
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 5

Expert Comment

by:waelothman
Comment Utility
the loop say for i =0  and whiel i < 0 and this not happend
0
 

Author Comment

by:icysmarty
Comment Utility
okay.. so, now I remove the for loop ...

size_t i=0;
      
      while(!feof(input_file))
      {
            fscanf(input_file,"%s%f%d",household[i].id_number,household[i].annual_income,household[i].members_of_household);
            i++;
      }

      return i;

This function returns an error when executing.. ( i believe it is pointer problem).
0
 
LVL 5

Accepted Solution

by:
waelothman earned 500 total points
Comment Utility
pleas don't forget & as i made
 fscanf(input_file,"%s%f%d",household[i].id_number,&household[i].annual_income,&household[i].members_of_household);
0
 

Author Comment

by:icysmarty
Comment Utility
You are right, i should have include the &
Weird though.. it reads the header and store them as an integer. ...
It suppose to read "name" then "salary" and "id"
I step through it, and it is actually reading 'na', 'a', 'm', 'e'...
so my household[i].id_number is somehow equal to (int)n
0
 

Author Comment

by:icysmarty
Comment Utility
Say I have

name             salary                   id
-----------------------------------------
can I discard this when reading the data?
or I should store then in a char array?
0
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
you shold discard this first in string like

fgets(s,80,input_fil);
wehere s is char array and 80 is the length of line +1 (for the new line) count it by your self
0
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
or
while( fgetc(input_file) != '\n'); //to skip the 1st line
while( fgetc(input_file) != '\n'); //to skip the 2st line
0
 

Author Comment

by:icysmarty
Comment Utility
I want to read the header and line as well, so I can print the exact data I read out to the screen.
I try to read the header and line inside the while loop but it somehow does not work.
The error "assertion fail" is displayed.
0
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
use
fgets(s,80,input_fil);
 where 80 is the line width
0
 

Author Comment

by:icysmarty
Comment Utility
Perfect, it is working now.
Can I ask you last question.
This function works when the data are organized row by row.
What if I have something like

No.1
John
         address     xxabc     go.get  

In c++, i believe I can use >>  to read the next string, but not sure if it can read the next word in a new line.
what can we use in C?
0
 
LVL 5

Expert Comment

by:waelothman
Comment Utility
you can fascanf many string and neglict what you don't want and get what you want like
fscanf(file,"%s%s%s%s%s",No,Name,Addressword,Address,Second);
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now