Reading from file into structure problem

  • (2 Pages)
  • +
  • 1
  • 2

24 Replies - 5665 Views - Last Post: 02 February 2010 - 02:57 PM Rate Topic: -----

#1 gaara87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 28-January 10

Reading from file into structure problem

Post icon  Posted 28 January 2010 - 07:16 AM

Hi everyone I cant seem to get this working and been trying for ages. Im got to read from a file which had multiple types of delimiters inbetween a students first name, 2nd name, math exam mark and english exam mark. I got arounf this using tokens but im having problems getting the information into the structure which was set up. I have tried to use students[1].forename = token; after the printf( "%s\n", token); but its giving me the error cannot convert from 'char *' to std::string[100] ive tried look online at what it means and I cant understand it :S can anyone please be of any help.


#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>

using namespace std;

int main()
{
		struct results {			
				string forename[100], *forenameptr;		
				string surname[100], *surnameptr;	   
				int math[100];			 
				int english[100];			   
				int overall;
			   
		}grade, student[100];  

		
		char *token;			
		char line[129];		  
		int l = 0;
	   

	   
		ifstream markdata ("results.txt");
				if (results.fail())
						{
								cerr << " Error cannot read file." << endl;
					}


		while (! results.eof())
		{
				results.getline (line,1000);
				token = strtok(line, " ");

						while (token !=NULL)
					{
								printf( "%s\n", token);
								token = strtok(NULL, " !,.£*^$&");

								printf( "%s\n", token);
								token = strtok(NULL, " !,.£*^$&");

								printf( "%s\n", token);
								token = strtok(NULL, " !,.£*^$&");

								printf( "%s\n", token);
								token = strtok(NULL, " !,.£*^$&");

								l++;

					}
		}

			   
}




Is This A Good Question/Topic? 0
  • +

Replies To: Reading from file into structure problem

#2 robob686  Icon User is offline

  • New D.I.C Head

Reputation: 7
  • View blog
  • Posts: 44
  • Joined: 24-April 09

Re: Reading from file into structure problem

Posted 28 January 2010 - 07:45 AM

Well with the
students[1].forename = token;


command, you are assigning the forename string a value of a character array, token. These are not the same thing as one is in the std library and the other is a cstring imported from the c language. Haven't checked it but this should work...
String temp = new String(token);
students[1].forename = temp;



Let me know if you still have trouble...

This post has been edited by robob686: 28 January 2010 - 07:46 AM

Was This Post Helpful? 1
  • +
  • -

#3 gaara87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 28-January 10

Re: Reading from file into structure problem

Posted 28 January 2010 - 07:53 AM

Thanks for the reply :D

I tried put the code in though i am unsure if its in the right place.

while (token !=NULL)
			{
				printf( "%s\n", token);
				string temp = new string(token);
				students[1].forename = temp;
				token = strtok(NULL, " !,.*^$&");

				printf( "%s\n", token);
				token = strtok(NULL, " !,.*^$&");

				printf( "%s\n", token);
				token = strtok(NULL, " !,.*^$&");

				printf( "%s\n", token);
				token = strtok(NULL, " !,.*^$&");

				l++;

			}
	}



when I did it this way it returned the errors.

error C2440: '=' : cannot convert from 'std::string' to 'std::string [100]' and error C2440: 'initializing' : cannot convert from 'std::string *' to 'std::basic_string<_Elem,_Traits,_Ax>'.
Was This Post Helpful? 0
  • +
  • -

#4 robob686  Icon User is offline

  • New D.I.C Head

Reputation: 7
  • View blog
  • Posts: 44
  • Joined: 24-April 09

Re: Reading from file into structure problem

Posted 28 January 2010 - 08:15 AM

Well, the first error means that the temp is a string (which we knew) and that
new string(token);


returns a string pointer. So you could create a pointer and assign it to new string(token), then assign the forename[1] to the value of that pointer. Kind of like this:
char s[] = {'q', 's', 'l', 'i'};
string t[5];
string* ptr = new string(s);
t[0] = *ptr;


So, the ptr variable holds the address of s in memory. When it is assigned to t[0], an asterisk is preceding the ptr variable to show that we want the value of what that is pointing to in the variable t[0].

That is just a general example, so try to incorporate that into your code and let me know if you can't get it to work...
Was This Post Helpful? 0
  • +
  • -

#5 gaara87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 28-January 10

Re: Reading from file into structure problem

Posted 28 January 2010 - 08:17 AM

View Postrobob686, on 28 Jan, 2010 - 07:15 AM, said:

Well, the first error means that the temp is a string (which we knew) and that
new string(token);


returns a string pointer. So you could create a pointer and assign it to new string(token), then assign the forename[1] to the value of that pointer. Kind of like this:
char s[] = {'q', 's', 'l', 'i'};
string t[5];
string* ptr = new string(s);
t[0] = *ptr;


So, the ptr variable holds the address of s in memory. When it is assigned to t[0], an asterisk is preceding the ptr variable to show that we want the value of what that is pointing to in the variable t[0].

That is just a general example, so try to incorporate that into your code and let me know if you can't get it to work...


okay thanks ill try now
Was This Post Helpful? 0
  • +
  • -

#6 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,340
  • Joined: 20-August 07

Re: Reading from file into structure problem

Posted 28 January 2010 - 08:31 AM

What does your input file look like?

Right now your code is a fragile mix of C and C++ - this is where your underlying problem is. you don't need to use pointers for any of this, nor do you need new, or strtok, or printf. If you get rid of all those, you'll hopefully be left with something which you can work with.

Do you have a book which explains how to use strings properly? you can replace 'strtok' with stringstreams - this should make your life easier

Also, your struct doesn't seem to make a great deal of sense -
        struct results {            
                string forename[100], *forenameptr;        
                string surname[100], *surnameptr;      
                int math[100];            
                int english[100];              
                int overall;
               
        }grade, student[100];   
What does a struct represent? does it represent one student? or does it represent 100 students? Before you start juggling arrays, try working with just one student first - when you have that working, adding extra students will be easier

This post has been edited by Bench: 28 January 2010 - 08:36 AM

Was This Post Helpful? 0
  • +
  • -

#7 gaara87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 28-January 10

Re: Reading from file into structure problem

Posted 30 January 2010 - 08:10 AM

View PostBench, on 28 Jan, 2010 - 07:31 AM, said:

What does your input file look like?

Right now your code is a fragile mix of C and C++ - this is where your underlying problem is. you don't need to use pointers for any of this, nor do you need new, or strtok, or printf. If you get rid of all those, you'll hopefully be left with something which you can work with.

Do you have a book which explains how to use strings properly? you can replace 'strtok' with stringstreams - this should make your life easier

Also, your struct doesn't seem to make a great deal of sense -
        struct results {            
                string forename[100], *forenameptr;        
                string surname[100], *surnameptr;      
                int math[100];            
                int english[100];              
                int overall;
               
        }grade, student[100];   
What does a struct represent? does it represent one student? or does it represent 100 students? Before you start juggling arrays, try working with just one student first - when you have that working, adding extra students will be easier




ah that was meant to be c++ based i didnt realise I was also using C :S. and example of the file which needs to be read is below:

Mark Ashton&12*76
Nick Andrews^68 80
Paul Farrel,51$62
Laura Green*42,45



The main reason i was running into problems originally was because I wasnt sure how to get rid of more than one type of delimiter and the only way i could find in a book was with tokens but I think I may have been looking too much and overcomplicated the problem. ill have a look in the book about stringstreams and see what I can find (though I think i got about tokens from the book so maybe the books on C :S)

This post has been edited by gaara87: 30 January 2010 - 08:15 AM

Was This Post Helpful? 0
  • +
  • -

#8 gaara87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 28-January 10

Re: Reading from file into structure problem

Posted 30 January 2010 - 08:18 AM

Also if you know of any good C++ books for beginners could you please tell me the name and ill try to find it as the oone I have at the moment doesnt seem to be much help.
Was This Post Helpful? 0
  • +
  • -

#9 Anarion  Icon User is offline

  • The Persian Coder
  • member icon

Reputation: 282
  • View blog
  • Posts: 1,456
  • Joined: 16-May 09

Re: Reading from file into structure problem

Posted 30 January 2010 - 08:22 AM

[ Here ] It's a free ebook from cplusplus.com. It's good for beginners :)
Was This Post Helpful? 1
  • +
  • -

#10 gaara87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 28-January 10

Re: Reading from file into structure problem

Posted 30 January 2010 - 08:31 AM

View PostAnarion, on 30 Jan, 2010 - 07:22 AM, said:

[ Here ] It's a free ebook from cplusplus.com. It's good for beginners :)


ah thanks ill have a look at it and hope it helps with the problem.
Was This Post Helpful? 0
  • +
  • -

#11 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,340
  • Joined: 20-August 07

Re: Reading from file into structure problem

Posted 30 January 2010 - 08:56 AM

View Postgaara87, on 30 Jan, 2010 - 03:18 PM, said:

Also if you know of any good C++ books for beginners could you please tell me the name and ill try to find it as the oone I have at the moment doesnt seem to be much help.

None of these books listed are free, but if you can spare the cash, look at these reviews for some of the best-of-breed beginner books.
- "Accelerated C++": http://accu.org/inde...e...ch&rid=1185
- "You Can Do It!": http://accu.org/inde...e...rch&rid=470
- "C++ Primer 4th Ed": http://accu.org/inde...e...rch&rid=778
- "Programming: Principles and Practice using C++": http://blog.cplusplu...d-practice.html

The first book (Accelerated C++) is fantastic if you're already familiar with at least one other programming language. Although it crams in 300 pages a level of useful information and detail which most books spend 1200 pages doing without all the additional 'clutter'.

"You Can Do It!" is a very gentle introduction; although it comes with a simple drawing (graphics) library and IDE attached to it which only work on Windows. Its specifically aimed at anyone who feels they need a slow, steady pace which goes as far to make programming a little bit more fun than simply writing characters on a console.

The final book, Princples and Practice using C++, is very recent - written by the creator of C++, Bjarne Stroustrup, and is probably one of the best student-level books out there. It teaches C++ in the context of problem solving and software development; so it goes beyond simply teaching the language in terms of what you can do - Bjarne emphasises the right and wrong ways to do things too - being the creator of the language, he knows what he's talking about.

The one thing all those books above have in common is that they do not teach anything about C except for a few foundation blocks which are carried over to C++ (things like int main, if statements, etc). You'll find that none of them really go into any detail about the C libraries; their focus will be on C++ tools, techniques, libaries, programming methodologies..
If I'm honest, as someone who learned C++ as a C programmer, the first time I really understood C++ was from the first of those books, and it made me realise how little of C is applicable or useful in C++. paradoxically, the more you know about 'C' the harder it can be to drop old habits and use C++ properly.

Also, avoid books which have things like "for dummies" or "21 days" etc in the title. and don't bother with any books by Herbert Schildt (The self-proclaimed "master" whose books demonstrate only his incompetence disguised as 'good advice')
Was This Post Helpful? 1
  • +
  • -

#12 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,340
  • Joined: 20-August 07

Re: Reading from file into structure problem

Posted 30 January 2010 - 09:54 AM

As for your string parsing problem, if I understand correctly, your data delimiters are !,.*^$&.

string and stringstream can both help here; stringstreams are ideal for separating out data which is delimited with a space. C++ has a replace algorithm function which you can use to replace your non-space delimiters with spaces;
#include <algorithm>
#include <string>

void substitute_delims(std::string& str)
{
    static const std::string delimiters = "!,.*^$&";

    for(size_t n(0); n!=delimiters.size(); ++n)
    {
        std::replace(str.begin(), str.end(), 
                     delimiters.at(n), ' ');
    }
} 


You can use an ifstream to read one line at a time - while data exists to be read - with getline. Note that getline is used as the conditional expression for the while loop. There's a very good reason for this; if getline fails for any reason, you won't end up running your program with corrupt/invalid data.
The most common cause for invalid data is that you reach the end of the data without hitting the end of the file (e.g there's an extra blank line at the end) - this usually leads to unwanted duplication or "ghost" data, and is the reason why you can't rely on "while not eof" to work properly
#include <sstream> 
while( std::getline( markdata, line ) )
{
    substitute_delims(line);
    std::istringstream buffer(line);

    std::string token;
    while( buffer >> token )
        std::cout << token << ' ';
    std::cout << '\n';
} 

This post has been edited by Bench: 30 January 2010 - 09:55 AM

Was This Post Helpful? 1
  • +
  • -

#13 gaara87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 28-January 10

Re: Reading from file into structure problem

Posted 30 January 2010 - 12:22 PM

View PostBench, on 30 Jan, 2010 - 08:54 AM, said:

As for your string parsing problem, if I understand correctly, your data delimiters are !,.*^$&.

string and stringstream can both help here; stringstreams are ideal for separating out data which is delimited with a space. C++ has a replace algorithm function which you can use to replace your non-space delimiters with spaces;
#include <algorithm>
#include <string>

void substitute_delims(std::string& str)
{
    static const std::string delimiters = "!,.*^$&";

    for(size_t n(0); n!=delimiters.size(); ++n)
    {
        std::replace(str.begin(), str.end(), 
                     delimiters.at(n), ' ');
    }
} 


You can use an ifstream to read one line at a time - while data exists to be read - with getline. Note that getline is used as the conditional expression for the while loop. There's a very good reason for this; if getline fails for any reason, you won't end up running your program with corrupt/invalid data.
The most common cause for invalid data is that you reach the end of the data without hitting the end of the file (e.g there's an extra blank line at the end) - this usually leads to unwanted duplication or "ghost" data, and is the reason why you can't rely on "while not eof" to work properly
#include <sstream> 
while( std::getline( markdata, line ) )
{
    substitute_delims(line);
    std::istringstream buffer(line);

    std::string token;
    while( buffer >> token )
        std::cout << token << ' ';
    std::cout << '\n';
} 


oh thanks for the information on the books and for the clear explanations of everything. Ive not done an other programming language before so found a copy of the programming book and going to start reading through that:)

tried to use the replace algorithm but when I put the code into the program I keep getting 3 similar errors:

Error 3 error C2780: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &,const _Elem)' : expects 3 arguments - 2 provided c:\users\syuhy\documents\visual studio 2008\projects\c+\cwork\2.cpp 35 f2

Error 1 error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &' from 'std::ifstream' c:\users\syuhy\documents\visual studio 2008\projects\c+\cwork\2.cpp 35 f2

Error 2 error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : could not deduce template argument for 'std::basic_string<_Elem,_Traits,_Alloc> &' from 'char [256]' c:\users\syuhy\documents\visual studio 2008\projects\c+\cwork\2.cpp 35 f2 (maybe because ive put char line[256] in the code earlier tried to change but no luck ':S)

though I cant work out what the errors mean. it did compile when i put in the remove_delim function so looking at the 2nd part to try and see whats wrong
Was This Post Helpful? 0
  • +
  • -

#14 gaara87  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 28-January 10

Re: Reading from file into structure problem

Posted 30 January 2010 - 01:37 PM

posted last message twice sorry

This post has been edited by gaara87: 30 January 2010 - 01:38 PM

Was This Post Helpful? 0
  • +
  • -

#15 Bench  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 857
  • View blog
  • Posts: 2,340
  • Joined: 20-August 07

Re: Reading from file into structure problem

Posted 31 January 2010 - 03:48 AM

View Postgaara87, on 30 Jan, 2010 - 07:22 PM, said:

though I cant work out what the errors mean. it did compile when i put in the remove_delim function so looking at the 2nd part to try and see whats wrong

What does your code look like which displays those errors?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2