Hey, ive written a piece of code which reads from a file called test.txt. all it does is use strtok to seperate the data from the spaces because there are alot of them, and then print them out, this worked fine when i did a test for just 1 line, but when i put this code in a while(!ins.eof()) loop, it reports a seg fault.... here is my code.

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
	ifstream ins;
	ins.open("test.txt", ios::in);
	char info[500];
	if(ins.good())
	{
		ins.getline(info, 500); // first line are just titles
		while(!ins.eof())
		{
			int found = 0;
			ins.getline(info, 500); 

			cout << info << endl;
			char *name = NULL;
			name = strtok(info, " "); // read in name

			char *dates = NULL;
			dates = strtok(0, " "); //read in dates
				
			char *dates2 = NULL; 
                                                // if the first element of dates is 0, 1, 2, dont read in dates2
			if(dates[0] == '0' || dates[0] == '1' || dates[0] == '2')
			{
				found = 0;
			}else{ // else read in 1 extra char (dates2)
				found = 1; 
				dates2 = strtok(0, " "); 
			}

			char *sold = NULL;
			sold = strtok(0, " ");

			char *minutes = NULL;
			minutes = strtok(0, " :");

			char *seconds = NULL;
			seconds = strtok(0, " ");
		
			cout << "name: " <<  name << endl;

			if(found == 1)
			{
				cout << "TRUEdate: " << dates << " " << dates2 << endl;
			}else if(found == 0){
				cout << "FALSEdate: " << dates <<endl;
			}
			cout << "sold: " << sold << endl;
			cout << "minutes: " << minutes << endl;
			cout << "seconds: " << seconds << endl;

			found = 0;

		}
		exit(1);
	}
	return 0;
}

for some reason it doesnt like me having the this peice of code in there

if(dates[0] == '0' || dates[0] == '1' || dates[0] == '2')
			{
				found = 0;
			}else{
				found = 1; 
				dates2 = strtok(0, " "); 
			}

but the point of this is to read in the day from the date section if the date isnt in the 24:60:60 time format....


test.txt contains

NAME   DATE    SOLD       TIME
    Sign   23:44:10 ?         0:00 
    Maria   Jul 11   ?         2:11
    Umama   Feb 11   ?         0:00
    Xtr   11:23:30 ?         103:03
    Fit   Sep 17   ?         0:00
    Ser    Dec 21   22231    0:00
    Rim    08:28:20 13322    0:00

just been tring to figure this out for ages, for some reason it also has a seg fault it i try to compare something that doesnt even do anything like...

if(dates[0] == 0)
{
      cout << "SOMEHTING" << endl;
}

is there something really that wrong with my code :| i cant see where ive gone wrong...

woot! fixed it :)

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.