Validating user input with text file

Hi, I need some assistance. I have two text file, fileName.txt and voteDate.txt. I am doing something which will allow user to select the option from the menu. Subsequently, it will print out the value from fileName.txt and user will input one of the print out value. After which, program will check if user input is the same as the file name value. If the same, it will proceed to print out the value from voteDate.txt whereby it will be a list of date. User will then input one of the date which the program show. If any of the user input does not match the text file value, it will show error and return to the main menu. Currently, I have the below code but I am unsure how to continue. Need some advice on this. Thanks.

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
#include <iostream>
#include <map>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

void main()
{
	int menu;
	ifstream inFile1;
	inFile1.open("fileName.txt");
	string name;

	ifstream inFile2;
	inFile2.open("voteDate.txt");
	string vote;
	
	string targetDate;
	string inputName;

	bool exit = false;
	while (exit==false) {
        cout << "Menu Option" << "\n" 
			<< "1. Highest Vote" << "\n"
			<< "2. Testing" << "\n"
			<< "4. Exit" << "\n" << "\n";
        cout << "Please select one of the option from above: ";
		cin >> menu;
		cout << endl;

		switch (menu) {
		case 1:
			{

		cout << "Name List" << endl;
		if (inFile1.is_open()) {
		while (getline (inFile1, name)) {	
			cout << name << '\n';
		}
		cout << "Please enter voter name: ";
		cin >> inputCode;
		
		cout << "Vote Date" << endl;
		if (inputCode == name)
			while (getline (inFile2, date)) {	
			cout << date << '\n';
		}
		cout << "\nPlease Enter voting Date (dd/mm/yyyy): ";
		cin >> targetDate;
		}

	Date date(targetDate);

			exit = false;
			break;
		}
			
		case 2:
			cout << "Test 2" << endl;
			break;

		case 4:
			exit = true;
			break;
		default:
			cout << "Error: Invalid input." << endl;
		}
	}
}
Last edited on
1. Are inputName and inputCode the same variable? I'm assuming so in my program below
2. If you wish to search the file for a particular name you can do so without printing all the names to console first using something like ..
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
int main()
{
    ifstream file("F:\\test.txt");
    string line;
    string inputName;
    cout<<"Please enter voter name: \n";
    cin>>inputName;
    bool match = false;
    if(file)
    {
        while(getline(file, line))
        {
            if(line == inputName)
            {
                cout<<"The name has been found!\n";
                match = true;
                break;
            }
        }
        if(match == false)
        {
            cout<<"Name not found\n";
        }
    }
}

3. Your program runs into trouble line 46 onwards because if(inputName == name) would only be true if the last name in the file was inputName. Otherwise even if inputName was found in the file this would still be false since the variable name holds the last name from the file at the end of the while() loop. It would be wiser to check against the bool defined above, so returning to my suggested code above you could carry on as ...
1
2
3
	if(match == true)//meaning the name has been found ... 
	inFile2.open("voteDate.txt");//... only then open the file, otherwise its not neeed	
	... do stuff withe inFile2

4. Date, line 54, seems to be a custom datatype but there is no definition of this struct/class in your program, nor a header file included
5. What is the point of case 2 in the switch currently or is it being prepared for future use
Hi gunnerfunner, thanks for your reply.
1) Yes, my apologises, inputName and inputCode is the same. I have forgotten to change
4) Does it requires any datatype if it is for date inserted as my program will have to enter a date
5) Case 2 is for my future use. I am doing it one by one.

I have tried to amend a little however, I am still confused with the program as there are too many if function. Currently, I have edited till this. Can advise if how should I edit it as after I insert the name, it will straight go to case 2 whereby it display "Test 2" and followed by the menu option

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
#include <iostream>
#include <map>
#include <string>
#include <fstream>
#include <sstream>

using namespace std;

void main()
{
	int menu;

	bool exit = false;
	while (exit==false) {
		cout << "Menu Option" << "\n" 
			<< "1. Highest Vote" << "\n"
			<< "2. Testing" << "\n"
			<< "4. Exit" << "\n" << "\n";
		cout << "Please select one of the option from above: ";
		cin >> menu;
		cout << endl;

		switch (menu) {
		case 1:
			{
				ifstream file1("fileName.txt");
				ifstream inFile2;
				string line;
				string inputName;
				cout << "Please enter voter name: \n";
				cin >> inputName;
				bool match = false;
				if(file1)
				{
					while(getline(file1, line))
					{
						if(line == inputName)
						{
							//cout<<"The name has been found!\n";
							match = true;
							if (match == true)
								inFile2.open("voteDate.txt");
							cout << "\nPlease Enter voting Date (dd/mm/yyyy): ";
							match = true;
							if(match == false)
							{
								cout << "Nothing found.\n";
							}
						}
					}	
				}
			}

		case 2:
			cout << "Test 2" << endl;
			break;

		case 4:
			exit = true;
			break;
		default:
			cout << "Error: Invalid input." << endl;
		}
	}
}
Last edited on
1. int main(), not void main() ...
2. practice uniform indentation style ... line 10 and line 14 brace styles are inconsistent
3. Exit should be case 3, not 4, as it stands ...
4. avoid unnecessary endl's (e.g line 21) unless you really want to flush the buffer, use cout<<"\n"; instead ...
5. at line 41, if match == true, you want to get out of the while loop and close file1 asap
5. there are various time and date formats in C++ (https://www.tutorialspoint.com/cplusplus/cpp_date_time.htm). For simplicity I'm using string to capture the inputDate. Your .txt file with the dates should be in corresponding format and if you don't like the string format you can use one from the link above. The following program has been tested with names and dates saved here: http://pastie.org/10966491
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
#include <iostream>
//#include <limits>//for cin.ignore() limits; 
#include <string>
#include <fstream>

using namespace std;

int main()
{
    bool exit = false;
    while (!exit)
    {
        cout << "Choose an Option \n1. Highest Vote \n2. Testing \n3 Exit \n";
        int menu;
        cin>>menu;
        /*  if(!(cin >> menu))//some sample code to validate user input, must use this/similar in 'real' programs
        {
            cout<<"Wrong entry, try again \n";
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            continue;
        }*/
        switch (menu)
        {//braces required for case 1 to scope local variables declared within this case;
            case 1:
            {
                ifstream file1("F:\\test.txt");
                bool match_name = false;
                if(file1)
                {
                    cout << "Please enter voter name: \n";
                    string inputName;
                    cin >> inputName;
                    string line;
                    while(getline(file1, line))
                    {
                        if(line == inputName)
                        {
                            match_name = true;
                            break;
                        }
                    }
                }
                else
                {
                    cout<<"Name file cannot be opened \n";
                }
                if(match_name == false)
                {
                    cout << "No matching name.\n";
                }
                else
                {
                    ifstream file2("F:\\test1.txt");//declare variables when & where needed ;
                    cout << "\nName found, now enter voting Date (dd/mm/yyyy): ";
                    string inputDate;
                    cin>>inputDate;
                    bool match_date = false;
                    if(file2)
                    {
                        string line;
                        while(getline(file2, line))
                        {
                            if(line == inputDate)
                            {
                                match_date = true;
                                cout<<"Date also found \n";
                                break;
                            }
                        }
                        if(match_date == false)
                        {
                            cout<<"No matching date for the name \n";
                        }
                    }
                }
            }
            break;
            case 2:
                cout << "Test 2" << endl;
            break;
            case 3:
                exit = true;
            break;
            default:
                cout << "Error: Invalid input. \n";
            break;
        }
    }
}



























Hi, thanks for explanation. I just realised that I should not be using the word "voting" but should be "bidding". And instead of name, it should be item (e.g. Toys, food, Household). But all this, I am able to change on my end.

I would like to enquire another issue. If after user input the date, I would want to retrive information from the file such as highest bid and time, where should I placed part of the code in? My file data will be something like this

Bidding Statistics
Time Price($) Quantity
8/10/2013 14:40 6.44 5
8/10/2013 14:40 6.38 2
8/10/2013 14:39 6.42 3
8/10/2013 14:39 6.15 1
8/10/2013 14:39 6.55 2
8/10/2013 14:39 6.55 3

I have the below code. However, for the BinarySearchTree (BST), I am still halfway through. I know how to do the decalration but unsure if the below code is correctly done to run my program.

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
BinarySearchTree<Bidding> bidding;
	items[inputName].getBidding(bidding, inputDate);

	double highBidding = -1;

	for (int i = 0, size = bidding.size(); i < size; i++)
	{
		Bidding bidding = bidding.get(i);

		if (highBidding == -1 || bidding.getPrice() > highBidding)
		{
			highBidding = bidding.getPrice();
		}
	}

	cout << "Item Code: " << inputName << endl;
	cout << "Date: " << inputDate.toString() << endl;
	cout << "Highest Bid: " << highBidding << endl;
	cout << "Bidding time(s): " << endl;

	for (int i = 0, size = bidding.size(); i < size; i++)
	{
		Bidding bidding = bidding.get(i);

		if (highBidding == bidding.getPrice())
		{
			cout << bidding.getTime().toString() << endl;
		}
	}
}



Last edited on
Using c++11 features ...
file1 is a list of names. file2 is the file provided in your latest post. I've removed the first 2 lines but if you wish to keep them you can just read off the first 2 lines into a dummy variable and then start working with the database
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
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
//#include <limits>//for cin.ignore() limits;
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    bool exit = false;
    while (!exit)
    {
        cout << "Choose an Option \n1. Highest Vote \n2. Testing \n3 Exit \n";
        int menu;
        cin>>menu;
        /*  if(!(cin >> menu))//some sample code to validate user input, must use this/similar in 'real' programs
        {
            cout<<"Wrong entry, try again \n";
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            continue;
        }*/
        switch (menu)
        {//braces required for case 1 to scope local variables declared within this case;
            case 1:
            {
                ifstream file1("F:\\test.txt");
                bool match_name = false;
                if(file1)
                {
                    cout << "Please enter voter name: \n";
                    string inputName;
                    cin >> inputName;
                    string line;
                    while(getline(file1, line))
                    {
                        if(line == inputName)
                        {
                            match_name = true;
                            break;
                        }
                    }
                }
                else
                {
                    cout<<"Name file cannot be opened \n";
                }
                if(match_name == false)
                {
                    cout << "No matching name.\n";
                }
                else
                {
                    ifstream file2("F:\\test1.txt");//declare variables when & where needed ;
                    cout << "\nName found, now enter voting Date (dd/mm/yyyy): ";
                    string inputDate;
                    cin>>inputDate;
                    vector<pair<string, double>> v;
                    if(file2)
                    {
                        string line;
                        while(getline(file2, line))
                        {
                            istringstream stream(line);
                            string date, time;
                            double price , qty;
                            stream >> date >> time >> price >> qty;
                            if(date == inputDate)
                            {
                                v.emplace_back(time, price);
                             }
                        }
                    }
                    if(v.empty())
                    {
                        cout<<"No matching date for the name \n";
                    }
                    else
                    {
                        sort(v.begin(), v.end(),[](const pair<string, double>&left, const pair<string, double>&right)
                        {return left.second > right.second;});
                        for (auto& elem : v)
                        {
                            cout<<elem.first<<": "<<elem.second<<"\n";
                        }
                    }
                }
            }
            break;
            case 2:
                cout << "Test 2" << endl;
                break;
            case 3:
                exit = true;
                break;
            default:
                cout << "Error: Invalid input. \n";
            break;
        }
    }
}
Topic archived. No new replies allowed.