File handling

Pages: 12
Hi...below is my code
So am trying to read and get information from firstfile that will then by used for a search
In secondfile..and well when i ran it a got errors..
I need serious help!!!!



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
  
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Applicant

{
public:

string getA();
string getB();
int getC();

private:

string A;
string B;
int C;
};



int main()
{
ifstream firstfile,secondfile;
firstfile.open("From Form.txt");
secondfile.open("StoreDatabase.txt");


string A;
string B;
int C;


firstfile >> A >> B >> C;
cout << "First Name: " << A << endl;
cout << "Surname: " << B << endl;
cout << "Registration Code: " << C << endl;

//from here am trying to search for registration code "C"

int offset;
string line;
secondfile.open("StoreDatabase.txt");
cin >> C;

if (StoreDatabase.is_open())
  {
   while (StoreDatabase.eof())
     {
      getline(infile2,line);
        if ((offet = line.find(C, 0)) != string::npos)
           {
               cout << "Found!" << C << endl;
            }

            fstream Confirmed;
           Confirmed.open("Confirmed_customers.txt",ios::out);
           if(!Confirmed_customers)
          {
         cout<<"Confirmed customers File creation failed";
         }
        else
        {
         cout<<"Confirmed_customers file successfuly created!";
         Confirmed<<"<< A << B << C <<";
         Confirmed.close();

        }
       infile2.close();
 }
 else
 cout <<"Could not find" << C <<endl;

fstream NotConfirmed;
NotConfirmed.open("NotConfirmed/Non customers.txt",ios::out);

if(!NotConfirmed)
{
cout<<"Non Customers File creation failed";
}
else
{
cout<<"Non Customers file Created!";
NotConfirmed<<"<< A << B << C <<";
NotConfirmed.close();

return 0;
}

Last edited on
Hi...below is my code

AND???

Do you have some kind of problem or question about your code?

Note: A decent indentation style would make your code a lot easier to read.
I am a humble beginer... that is unable to run even it could it can just read from first file but i want to do more...i want it to search from the second file and write to two different file that it will create
What exactly is wrong with the program? Why doesn't it run? You need to explain exactly what is happening, not just post gibberish that doesn't make any sense. If you get error/warning messages from your compiler, post them exactly as they appear in your development environment.



Hello Chewe Kennedy,

As jlb said with proper indenting you code would look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Applicant

{
	public:
		string getA();
		string getB();
		int getC();

	private:
		string A;
		string B;
		int C;
};

int main()
{
	ifstream firstfile, secondfile;
	firstfile.open("From Form.txt");
	secondfile.open("StoreDatabase.txt");


	string A;
	string B;
	int C;


	firstfile >> A >> B >> C;

	cout << "First Name: " << A << endl;
	cout << "Surname: " << B << endl;
	cout << "Registration Code: " << C << endl;

	//from here am trying to search for registration code "C"

	int offset;
	string line;

	secondfile.open("StoreDatabase.txt");

	cin >> C;

	if (StoreDatabase.is_open())
	{
		while (StoreDatabase.eof())
		{
			getline(infile2, line);
			if ((offet = line.find(C, 0)) != string::npos)
			{
				cout << "Found!" << C << endl;
			}

			fstream Confirmed;

			Confirmed.open("Confirmed_customers.txt", ios::out);

			if (!Confirmed_customers)
			{
				cout << "Confirmed customers File creation failed";
			}
			else
			{
				cout << "Confirmed_customers file successfuly created!";
				Confirmed << "<< A << B << C <<";
				Confirmed.close();

			}
			infile2.close();
		}
	else
		cout << "Could not find" << C << endl;

	fstream NotConfirmed;
	NotConfirmed.open("NotConfirmed/Non customers.txt", ios::out);

	if (!NotConfirmed)
	{
		cout << "Non Customers File creation failed";
	}
	else
	{
		cout << "Non Customers file Created!";
		NotConfirmed << "<< A << B << C <<";
		NotConfirmed.close();

		return 0;
	}

Then after running it through a compiler, using the one here, I got this:

 In function 'int main()':
47:6: error: 'StoreDatabase' was not declared in this scope
51:12: error: 'infile2' was not declared in this scope
52:9: error: 'offet' was not declared in this scope
61:9: error: 'Confirmed_customers' was not declared in this scope
74:2: error: expected '}' before 'else'
40:6: warning: unused variable 'offset' [-Wunused-variable]
91:2: error: expected '}' at end of input


First you should try to fix all the errors that you can and ask about the ones that you do not understand.

Also since you are reading from a file post the contents of the file or a good sample to work with, so everyone can work with the same information.

There are parts of the code that need reworked because what you have may not work the way that you are thinking of.

Andy
Thanks for the clarification Andy i will post again after rework..
Jlb thanks for your contribution...
I appreciate all
Hello Hello Chewe Kennedy,

I work with your program a bit and came up with this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

class Applicant
{
	public:
		Applicant(std::string firstName, std::string surname, int regCode) :
			m_firstName(firstName), m_surname(surname), m_regCode(regCode) {}

		string getFirstName() { return m_firstName; }
		string getSurname() { return m_surname; }
		int getRegCode() { return m_regCode; }

	private:
		string m_firstName;
		string m_surname;
		int m_regCode;
};

int main()
{
	ifstream inFileFF("From Form.txt"), inFileStore("StoreDatabase.txt");

	//inFileFF.open("From Form.txt");
	//inFileStore.open("StoreDatabase.txt");

	if (!inFileFF)
	{
		std::cout << "\n     File \" From Form.txt\" did not open!\n";

		return 1;
	}

	if (!inFileStore)
	{
		std::cout << "\n     File \" From Form.txt\" did not open!\n";

		return 2;
	}

	string firstName;
	string surname;
	int regCode{};

	inFileFF >> firstName >> surname >> regCode;

	cout << "First Name: " << firstName << endl;
	cout << "Surname: " << surname << endl;
	cout << "Registration Code: " << regCode << endl;

I fixed up the class a little, but since you never use it I am not sure if it will help.

When opening a file stream it is a must that you check that it is open. The 2 if statements, lines 30 - 42, do this and if there is a problem the program exits with the "return 1". With a "return" statement (0) zero means that there was no problem and any number other than (0) zeor, usually a positive number, means there is a problem. Just one way of tracking down where it went wrong.

This way you leave the program if there is a problem opening the file streams to have a chance to fix it as opposed to continuing on with the program and may be have to do a second check or run the program with an if/else statement and about half of what I have seen they forget the else part to say that the file did not open.

In the next part:
56
57
58
59
60
61
62
	int offset{}, regCodeToFind{};
	string line;

	// inFileStore.open("StoreDatabase.txt");

	// <--- Needs a prompt
	cin >> regCodeToFind;

Line 59 will cause a problem trying to open a file stream that is already open.

After that point and without seeing the input file and having a better idea of what you need to do I am stuck for the moment.

Andy
Thanks again Andy..!
The idea of the program is that,it should not get input from a user but reading from the "from form" file where it gets the first name,surname,the regcode and then storing them a variables..using reg code as the search key,it search in the storedatabase.txt,if the regcode is found in the storedatabase.txt it as well compares if the firstname and the surname if they are the same with those stored in the variables.and finally if the condition is true it writes a new file called confirmedCustomers.txt if else it writes to a different file called unconfirmedCustomers.txt....

That is what the rest of the code should do...my face is blue
Last edited on
Hello Chewe Kennedy,

Sorry for the delay. It got late and I kind of crashed last night.

The code I posted is good to the last line, for the most part.

Starting with the line if (StoreDatabase.is_open()) everything from here needs reworked.

Some of what you did may be usable, but may not be the correct approach.

This part of the program needs to read one file and compare it to the contents of another file.

I was thinking your choices are:

1. Open and close the "StoreDatabase.txt" file stream everytime that you need it. Probably the least efficent.

2. Open the file and clear the state bits when finished then move the file pointer back to the beginning to read the file again.

3. Store each record in an array of classes or a vector would be a better choice. Then you would have a more efficient way dealing with the information in the "StoreDatabase.txt" file. You could compare individual variables this way instead or having to decompose a string for what you want.

There are other options, but I do not think you are ready for them yet.

Personally I would use a vector, but in the end you know better what you can and can not do, so the choice is yours.

Getting back to if (StoreDatabase.is_open()). This has a couple of problems. First you are trying to check the file name when you should be checking the file stream. Second just because the file stream is open does not mean that you can use it. Third the file stream is considered open until you execute a "close", so the condition will always be true as long as the stream is open. This may not be what you want. using if (!inFileStore) is a better choice to catch any problems.

Andy
Understood...lets say i was to go for the third choice "Store each record in an array of classes or a vector" what would be the code??
I would like to to see the actual code
Last edited on
 
	if (StoreDatabase.is_open())
is where am having the most problems
And it appears you are the only one helping here...i so grateful Andy
And it appears you are the only one helping here...i so grateful Andy


That is partly because of things like "is where am having the most problems". This "question" tells us nothing, you need to learn to actually ask meaningful questions that actually tell us something about your problem.

Why is that line of code causing you problems?

By the way do you realize that there are multiple causes for errors when dealing with file streams. It is usually a bad practice to only check for a single problem like is_open(), better to check for all the different errors with something like if(!StoreDatabase) instead. I recommend testing the state of the stream immediately after trying to open them, and take some action right away, which probably means exiting the program with an error message.

Also using eof() to control an input loop is usually a source of errors, you should use the actual read of the file instead.
Instead of:
1
2
3
   while (StoreDatabase.eof())
     {
      getline(infile2,line);


The following is considered more acceptable:
1
2
while(getline(YourInputStream, line))
    {


And as Andy already said most of your "read loop" needs to be redone/thrown out and replaced.

Another turn off, for me at least is statements like:
what would be the code??
I would like to to see the actual code



This is your assignment asking for someone to do the work for you is a bad omen because you usually will not learn much when you have someone else just "give you the code".

Please post the contents of From Form.txt and StoreDatabase.txt. If they are too big then post some representative sample of their contents - enough to use in test run. If this is an assignment then please post the full assignment text. We ask this because beginners frequently miss some detail that affects how the program should be written.

Looking at your original code:
- why do you open secondfile twice (lines 30 and 47)?
- You read C at line 41 and again at line 48. Is that intentional?

- The loop at line 52 will never run. Since your looping while the file is at the end instead while it is not at the end. Using end-of-file is actually a bad way to do this since eof won't be true until the program tries to read past the end. Replace lines 52-54 with:
while (getline(infile2,line)) {

- You open and close confirmed each time you write to it. I'm not certain, but I think each time you open it, it clears the contents and writes at the beginning, so every write blows away whatever was written before. You could fix this by opening it in append mode, but it would be easier and clearer if you just opened it once.

It appears that you're trying to separate the input file contents into the "confirmed" file and the "not confirmed" file. If that's true then Andy's point about indentation should show that you need to rearrange the logic.

Line 55 is probably insufficient for what you want. You're just searching for the registration code in the entire line of text. What if the registration code shows up in the customer's name? What if you're looking for registration code ABC and there's a line with registration code ABCD? You'd think that ABCD is confirmed.

It sounds like you need functions to read and write an applicant. The loop should be (in pseudo-code)
1
2
3
4
5
6
7
while (read an applicatant) {
    if (application.registrationCode == inputRegistration code) {
        write applicatant to confirmed file
   } else {
        write applicant to unconfirmed file
   }
}

Thanks dhayden (5001)

the contents from form file are



   Lucy           Mubanga             2562346    
  Mark            Bwalya               2436586  
  Kennedy       chewe               7483289 
  Lisa              Phiri                  3674765  
  Chitalu         Malama              4672762  
  Frank           Tambo              6546727  
  Malika          Chewe              4729208  
  Raymod        Daka                3894782  
  Lucy             Kalinga             5849535 
  Jack             Kakwekwe        7548394  
   Oka             gjriudf             6458934  
  Emmanucle   Fuka               4325673  
  Brian            Mwale             5327834  
  Lisa              MWeka            1895865  


where as the StoreDatabase contents are;


  Lucy                Mubanga         2562346  
  Mark               Bwalya            2436586  
  Kennedy         chewe              7483289  
  Lisa                Phiri                3674765  
  Chitalu           Malama            4672762 
  Naomi            Kanaka            6436728  
  Malika            Chewe             4729208  
  Raymod         Daka                3894782  
  Lucy              Kalinga             5849535  
  Jack              Kakwekwe         7548394 
  Emmanucle    Fuka                 4325673  
  Brian             Mwale               5327834  
  Lisa               MWeka              1895865  
  Prince            MWamba            4563982   
  


why do you open secondfile twice (lines 30 and 47)?

That was a mistake..thanks

You read C at line 41 and again at line 48. Is that intentional?

yes it was but i stand corrected,

1
2
3
4
firstfile >> A >> B >> C;
cout << "First Name: " << A << endl;
cout << "Surname: " << B << endl;
cout << "Registration Code: " << C << endl; 


on this these lines i was trying read them in,am accepting comments and corrections

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
int offset;
string line;
secondfile.open("StoreDatabase.txt");
cin >> C;

if (StoreDatabase.is_open())
  {
   while (StoreDatabase.eof())
     {
      getline(infile2,line);
        if ((offet = line.find(C, 0)) != string::npos)
           {
               cout << "Found!" << C << endl;
            }

            fstream Confirmed;
           Confirmed.open("Confirmed_customers.txt",ios::out);
           if(!Confirmed_customers)
          {
         cout<<"Confirmed customers File creation failed";
         }
        else
        {
         cout<<"Confirmed_customers file successfuly created!";
         Confirmed<<"<< A << B << C <<";
         Confirmed.close();

        }
       infile2.close();
 }
 else
 cout <<"Could not find" << C <<endl;

fstream NotConfirmed;
NotConfirmed.open("NotConfirmed/Non customers.txt",ios::out);

if(!NotConfirmed)
{
cout<<"Non Customers File creation failed";
}
else
{
cout<<"Non Customers file Created!";
NotConfirmed<<"<< A << B << C <<";
NotConfirmed.close();


You read C at line 41 and again at line 48. Is that intentional?

-line 48 was trying to get the variable "Registration code" which will be the search key in the storeDatabase,

let me explain the code as i wrote it


1
2
3
4
5
6
7
 if ((offet = line.find(C, 0)) != string::npos)
           {
               cout << "Found!" << C << endl;
            }

            fstream Confirmed;
           Confirmed.open("Confirmed_customers.txt",ios::out);


the above part of the code am trying to do is;
-if the Registration code is found,it then compares the names stored in string varibles A and
B....

Then:
- if the string variables in A and B (names)are the same as the ones in the storeDatabase

1
2
3
4
5
6
7
8
9
10
11
12
fstream Confirmed;
           Confirmed.open("Confirmed_customers.txt",ios::out);
           if(!Confirmed_customers)
          {
         cout<<"Confirmed customers File creation failed";
         }
        else
        {
         cout<<"Confirmed_customers file successfuly created!";
         Confirmed<<"<< A << B << C <<";
         Confirmed.close();

-the program creates a new file where the confirmed customers are written,the format being
First Name| Surname | Registration Code
- - -

-or else it creates a different file Not confirmed customers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 else
        {
         cout<<"Confirmed_customers file successfuly created!";
         Confirmed<<"<< A << B << C <<";
         Confirmed.close();

        }
       infile2.close();
 }
 else
 cout <<"Could not find" << C <<endl;

fstream NotConfirmed;
NotConfirmed.open("NotConfirmed/Non customers.txt",ios::out);

if(!NotConfirmed)
{
cout<<"Non Customers File creation failed";
}
else
{
cout<<"Non Customers file Created!";
NotConfirmed<<"<< A << B << C <<";
NotConfirmed.close();

return 0;
}



Thats what am trying to do with this program


Last edited on
Thanks for posting. Can you post the assignment? So far what I understand is:
THe user enters a registration code.
You read through storedatabase.txt. If a line matches the registration code, print it to confirmed_customers.txt. Otherwise print it to unconfirmed_customers.txt

The format of storeddatabase.txt is:
first_name sur_name gender registration_code

Do I understand correctly so far?

Here is your code, with indentation to match the actual structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    int offset;
    string line;
    secondfile.open("StoreDatabase.txt");
    cin >> C;

    if (StoreDatabase.is_open()) {
	while (StoreDatabase.eof()) {
	    getline(infile2, line);
	    if ((offet = line.find(C, 0)) != string::npos) {
		cout << "Found!" << C << endl;
	    }

	    fstream Confirmed;
	    Confirmed.open("Confirmed_customers.txt", ios::out);
	    if (!Confirmed_customers) {
		cout << "Confirmed customers File creation failed";
	    } else {
		cout << "Confirmed_customers file successfuly created!";
		Confirmed << "<< A << B << C <<";
		Confirmed.close();

	    }
	    infile2.close();
	}
	else
	cout << "Could not find" << C << endl;

	fstream NotConfirmed;
	NotConfirmed.open("NotConfirmed/Non customers.txt", ios::out);

	if (!NotConfirmed) {
	    cout << "Non Customers File creation failed";
	} else {
	    cout << "Non Customers file Created!";
	    NotConfirmed << "<< A << B << C <<";
	    NotConfirmed.close();
	}

Line 8: you're reading from the infile2, which doesn't exist.
Line 15: confirmed_customers isn't defined
Line 26: this else doesn't match an if. Note that it's outside the while loop. It looks like it's meant to go at line 12 like this:
1
2
3
4
5
            if ((offet = line.find(C, 0)) != string::npos) {
                cout << "Found!" << C << endl;
            }
            else
                cout << "Could not find" << C << endl;


Lines 28-37 need to go inside the loop
jlb (4616)
i appreciate the effort am just stuck,am learning either way
Hello Chewe Kennedy,

Had you posted the input files earlier I would have told you that you are not reading the files correctly.

Just because you want "firstName", lastName" and "regCode" does not mean that it will skip all the other fields in the file.

When you sayinFileFF >> firstName >> lastName >> regCode; what you will end up with is "firstName" will contain "Lucy", "lastName" will contain "Mubanga" and "regCode" would fail when trying to put a letter into a numeric variable. Then after that "inFileFF" would not be able to read anything else.

For whatever the field is in the input file you have to account for each field or you will throw off the rest of the reads.

After you read a line completely and deal with each only then can you compare the two files and process them the way you need.

One of the things you have not mentioned is what the actual requirements of the program are. It helps to understand what the program should do and what you need to do.

Andy
i appreciate the effort am just stuck,am learning either way

Well I don't see any "learning" being accomplished in this thread. Your last post has the same "errors" that have been pointed out several times. If you were learning you would at least tried to fix the issues that have been pointed out.

So stick with it, I'm sure someone will give you the code you so desire, good luck.

The assignment reads
A local store is offering a 50% discount on selected items to registered regular customers,for the discount customers are to submit their Names(First Name and Surname) and the registration Code through the online Website of which data will be extracted and saved as From form.to avoid irregular customers from this taking part,as a program you are hired to write a program that will read information from the entry (online form) and checks if the entered Registration code together with the name exists in the stores database,then it creates and writes to two file confirmed/not confirmed



and the above code is what i have done for,and please to say this is my first time using this platform,but promise i will be a clear
dhayden (5002)

above is the question.
THe user enters a registration code.

-yes through the online website,then the data is extracted to the from form file.txt
thank you in advance!

Handy Andy (3614)
My mistake,new things maybe overwhleming but there is the question.
and at the moment like you advised am trying to revise through vectors...

Last edited on
Pages: 12