Searching 2D array

I am attempting to search for a string value in a 2D array based upon an inputted username. This code builds, but does not correctly search it. Please help

1
2
3
4
5
6
7
8
9
10
11
12
 	int x, y; 
	bool found = false; 
	for (x = 0, y = 0; x < 5, y < 7; x++, y++)
	{
		if (theAccounts[x][y] == username)
		{
			found = true; 
			saveRow = x; 
			break; 
		}
	}
What is theaccounts?

your loop iterates on the diagonal until x is 5. It does x = 0, y= 0, then x = 1, y=1, then x=2, y=2...

because you made a 2-d structure, you now need 2 nested loops..

for(x = ...)
for(y = ...)
now try it
theAccounts is the array that has the stored data from this file.

bham@gnet.com Blake Ham squid62 1987 U Teacher
jdark@att.net Jim Dark gymrat32 1985 A Master
hdgreen@lakes.net Hannah Green flower22 2007 U Apprentice
tsmith@dna.com Tom Smith tuna20 2000 U Teacher
jarrow@pnet.com James Arrow ahoy10 2005 U Apprentice
1
2
3
4
5
6
7
8
for (int x = 0; x < 5; x++)
		{
			for (int y = 0; y < 7; y++)
			{
				inputFile >> theAccounts[x][y];
			}
			cout << endl;
		}


Is this correct code for inputting data from a .txt document into a 2D array? The only username and password it is finding right now is the top row.
instead of 2D array consider using a struct/class:
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
# include <iostream>
# include <string>
# include <vector>
# include <fstream>
# include <sstream>
# include <algorithm>
# include <sstream>

struct Account
{
    std::string m_email;
    std::string m_firstName;
    std::string m_lastName;
    std::string m_userName;
    double m_year;
    char m_classification;
    std::string m_designation;

    Account(const std::string& email, const std::string& firstName, const std::string& lastName,
             const std::string& userName, double year, char classification, const std::string& designation)
    : m_email(email), m_firstName(firstName), m_lastName(lastName), m_userName(userName), m_year(year),
        m_classification(classification), m_designation(designation){}
    //member initialization
};
std::ostream& operator << (std::ostream& os, const Account& a)
{
    os << a.m_email << " " << a.m_firstName << " " << a.m_lastName << " " << a.m_userName
        << " " << a.m_year << " " <<  a.m_classification << " " << a.m_designation << " \n";
    return os;
    //helper function for printing Account objects
}

int main()
{

    std::ifstream inFile{"C:\\test.txt"};
    std::vector<Account> theAccounts{};

    if(inFile)
    {
        std::string line{};
        while (getline(inFile, line))
        {
            std::istringstream stream{line};
            std::string email, firstName, lastName, userName, designation;
            double year{};
            char classification{};
            stream >> email >> firstName >> lastName >> userName >> year >> classification >> designation;
            //std::istringstream parses on white-space
            if(inFile)
            //check the file is still open to avoid spurious reads
            {
                theAccounts.emplace_back(Account(email, firstName, lastName, userName, year, classification, designation));
                //in-situ construction of Account instances
            }
        }
    }
    for (const auto& elem : theAccounts)std::cout << elem;
    //sanity-check

    std::cout << "Enter username to find: \n";
    std::string userName{};
    getline(std::cin, userName);

    auto itr = std::find_if(theAccounts.cbegin(), theAccounts.cend(), [&userName](const Account& a)
           { return a.m_userName == userName;});
   //http://en.cppreference.com/w/cpp/algorithm/find

    if (itr != theAccounts.cend())
    {
        std::cout << *itr;
    }
    else
    {
        std::cout << "Username doesn't exist \n ";
    }
}
theAccounts is the array that has the stored data from this file.

This I knew :)
I am going to assume its type is string for now. since I still do not know for sure

enum cols
{
email, fname, lname, webname, dob, type, title, colmax
};

string theaccounts[maxdata][colmax]; //maxdata is* of expected rows..

one way to read it:
for(i = 0; i < numrows; i++)
{
file >> theaccounts[i][email];
file >> theaccounts[i][fname];
... all the data elements
}

one way to search it

for(i = 0; i < numrows; i++)
{
if(theaccounts[i][email] == somestring) //example to search on 2 of the fields
if(theaccounts[i][dob] == anotherstring) //you can and these up, whatever
foundit();
}


Does all that make sense?
I named the columns, to make life easier, using the enum. If you need more columns, you can just add them and the code still works because the columns are named. In a bigger program you want to put the enum in a namespace.

Likely, as stated, you need a class. The array solution I provide is 1) in case you havent seen classes yet or 2) you don't need anything more, making a class overkill. If you are not doing much, sometimes a plain old array is a sufficient container, or a vector if you want algorithms (like find?? maybe??). Vector and find would eliminate some of your woes.

Last edited on
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstring>
#include <vector>

using namespace std;

void showAll(string[5][7]);
void sortInput(string[5][7]);
bool readFile(string[5][7]);
bool validateUser(string[5][7], string, string, int &);

//Techi Gadgets Account Program
//Rohan S. Jakhete
//6/11/2017
//COP 2000

int main()
{
	string username, password;
	int saveRow, position, userInput = 1;
	string accountData[5][7] = { " " };
	readFile(accountData);

	if (readFile(accountData))
		cout << "File Read Successfully";

	else
	{
		cout << "Invalid file, exiting.";
		return 0;

	}

	do
	{
		cout << endl << "Enter the following information or zero to exit";
		cout << endl << "Please Enter Your User Name >";
		cin >> username;
		if (username == "zero")
			return 0;
		cout << endl << "Please Enter Your User Password >";
		cin >> password;
		if (password == "zero")
			return 0;
		validateUser(accountData, username, password, saveRow);
		if (validateUser(accountData, username, password, saveRow))
		{
			cout << endl << "Welcome Back" << accountData[saveRow][1];

			if (accountData[saveRow][5] == "A")
			{
				sortInput(accountData);
				showAll(accountData);

				ofstream outputFile;
				outputFile.open("sortedBackup.txt");

				for (int a = 0; a < 5; a++)
				{
					for (int b = 0; b < 7; b++)
					{
						outputFile << accountData[a][b];
					}
					cout << endl;
				}
				if (outputFile)
				{
					cout << endl << "Backup File Completed";
					continue;
				}
				else
				{
					cout << endl << "Error Saving File, exiting....";
					return 0;
				}
			}

			else
			{
				cout << endl << accountData[saveRow][1] << "   " << accountData[saveRow][2] << "   " << accountData[saveRow][4] << "   " << accountData[saveRow][5] << "   " << accountData[saveRow][6];
				continue;
			}
		}

		else
		{
			cout << endl << "Username and Password do not match...Please try Again";
			continue;
		}




	} while (userInput != 0);


	return 0;
}

void showAll(string theAccounts[5][7])
{
	for (int x = 0; x < 5; x++)
	{
		for (int y = 0; y < 7; y++)
		{
			cout << setw(8) << theAccounts[x][y] << " ";
		}
		cout << endl;
	}
}

void sortInput(string theAccounts[5][7])
{
	bool swap;
	string temp;

	do
	{
		swap = false;
		for (int x = 0; x < 4; x++)
		{
			if ((theAccounts[x][1]) > (theAccounts[x + 1][1]))
			{
				temp = theAccounts[x][1];
				theAccounts[x][1] = theAccounts[x + 1][1];
				theAccounts[x][0] = theAccounts[x + 1][0];
				theAccounts[x][2] = theAccounts[x + 1][2];
				theAccounts[x][3] = theAccounts[x + 1][3];
				theAccounts[x][4] = theAccounts[x + 1][4];
				theAccounts[x + 1][1] = temp;
				swap = true;

			}
		}

	} while (swap);
}

bool readFile(string theAccounts[5][7])
{
	ifstream inputFile;
	inputFile.open("C:/Users/rohan/Desktop/AccountData.txt");

	if (inputFile)
	{
		for (int x = 0; x < 5; x++)
		{
			for (int y = 0; y < 7; y++)
			{
				inputFile >> theAccounts[x][y];
			}
			cout << endl;
		}
		return true;
	}

	else
	{
		return false;
	}

}

bool validateUser(string theAccounts[5][7], string username, string password, int &saveRow)
{
	int x, y;
	bool found = false;
	for (x = 0, y = 0; x < 5, y < 7; x++, y++)
    {
        for (y = 0; y < 7; y++)
        {
            if (theAccounts[x][y] == username)

			found = true;
			saveRow = x;
			break;
        }
        cout << endl;
    }
	cout << endl << x;
	switch (saveRow)
	{
	case 0:
		if (password == "squid62")
		{
			return true;
		}
		else
			return false;
	case 1:
		if (password == "gymrat32")
		{
			return true;
		}
		else
			return false;
	case 2:
		if (password == "flower22")
		{
			return true;
		}
		else
			return false;
	case 3:
		if (password == "tuna20")
		{
			return true;
		}
		else
			return false;
	case 4:
		if (password == "ahoy10")
		{
			return true;
		}
		else
			return false;
	}

}


I have to use 2D arrays. I did not get what you meant. This is the whole code, maybe if you look at it as a whole, it will make more sense. There is datbase, and based on username, and password, it has to validate user.
Topic archived. No new replies allowed.