[C++] Reading from a Text File

First post updated with the RIGHT code

Page 1 of 1

9 Replies - 2226 Views - Last Post: 19 September 2008 - 02:30 PM Rate Topic: -----

#1 CalumJR  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 10-May 08

[C++] Reading from a Text File

Post icon  Posted 18 September 2008 - 08:18 AM

Can I just say I would be extremely grateful if somebody could help me with this as I know some people will find it very simple - I am only a beginner you see :) Thank you in advance.


Problem:

I have been using a username & password function which I found & edited myself to work with my program; however, the way they saved the username & password to text files is different to the way I have done it in my "createAccount()" function.

The code I was using saved the username to a text file called "username.txt" & the password to another text file called "password.txt". When creating my own "createAccount()" function I didn't think it would be best to do it this way when creating multiple accounts; therefore in my "createAccount()" function, I saved just one text file for both the username & password. The username is the title of the text file & the password is what is contained within the text file. E.g. if a user of my program is called Arun, the name of the text file would be called "Arun.txt" & his password would be the only thing in that file.

This is where I am stuck. My "createAccount()" function works perfectly & saves the file where & how it should do; however, I cannot seem to change the code I already had for my "authorisation()" - or 'login' to use a better word - function. This function works perfectly when reading in the original "username.txt" & "password.txt" files, but when I try & read the one file I have created instead, it just doesn't seem to work.

I would like the "authorisation()" function to read the file created in the "createAccount()" function & check that the username (the title of the text file) & the password (what is contained in that file) are both correct.

I will now show you the following code: My fully functioning code for the "createAccount()" function to show you how I have done it; the original "authorisation()" function which works with the two files - before I have modified it; & the modified "authorisation()" function to read the files created by the "createAccount()" function:


My fully functioning code for the "createAccount()"

void createAccount(int& keyPressed, int& currentMonth, int& currentYear)
{//start of 'createAccount' function which allows the user to create a new accout in order to login to the program

	int getKeyPress();
	void displayHeaderFooter( int& currentMonth, int& currentYear);

	CLEAR_SCREEN();

	displayHeaderFooter(currentMonth, currentYear);

	Gotoxy(23, 12);
	SelectTextColour( clCyan);
	cout << "Please enter your desired username.";
	Gotoxy(44, 10);
	cin >> username;
	Gotoxy(23, 13);
	SelectTextColour( clDarkCyan);
	cout << "Please enter your desired password.";
	Gotoxy(44, 11);
	cin >> password;

	ofstream outputFile;
	outputFile.open(userFile.c_str(), ios::out);
	outputFile << password;
	outputFile.close();

}//end of 'createAccount' function




The original "authorisation()" function:

void authorisation(int& keyPressed, int& currentMonth, int& currentYear)
{//start of the 'authorisation' function which allows the user to login
	
	int getKeyPress();
	void displayHeaderFooter( int& currentMonth, int& currentYear);
	void displayMenu(int& keyPressed, int& currentMonth, int& currentYear);
	
	CLEAR_SCREEN();

	displayHeaderFooter(currentMonth, currentYear);
	
		ifstream Passfile("password.txt", ios::in);
		Passfile >> inputPassword;
		ifstream Userfile("username.txt", ios::in);
		UserFile >> inputUsername;
		Gotoxy(26, 12);
		SelectTextColour( clCyan);
		cout << "Please enter your username.";
		Gotoxy(44, 10);
		cin >> username;
	Gotoxy(26, 13);
	SelectTextColour( clDarkCyan);
		cout << "Please enter your password.";
		Gotoxy(44, 11);
	cin >> password;
		Passfile.close();
		Userfile.close();

	if (username == inputUsername && password == inputPassword)
	{
		Gotoxy(23, 18);
		SelectTextColour( clGreen);
		SelectBackColour( clBlack);
		cout << "You have logged in successfully.";
		Gotoxy(15, 19);
		cout << "Please press the 'M' key to display the Main Menu."; 
	
	}

	while (username == inputUsername && password == inputPassword)
	{
		userHeader = 1;	 
		
		if (userHeader == 1)
		{
			Gotoxy(0, 0);
			SelectTextColour( clGrey);
			SelectBackColour( clDarkCyan);
			cout << "		" << username << "		  ";
			SelectBackColour( clBlack);
		}	
	
		keyPressed = getKeyPress();
		if (keyPressed == 'M')
		{
			CLEAR_SCREEN();
			displayHeaderFooter(currentMonth, currentYear);
			displayMenu(keyPressed, currentMonth, currentYear);
		}
		else
		{
			Gotoxy(16, 18);
			SelectTextColour( clRed);
			cout << "\a";
			cout << "The command you entered is invalid.";
			Gotoxy(13, 19);
			cout << "Please press the 'M' key to display the Main Menu.";
		}
	}
	
		 
	if (username != inputUsername || password != inputPassword)
	{
		 Gotoxy(16, 18);
		 SelectTextColour( clRed);
		 cout << "\a";
		 cout << "The username or password you entered is invalid.";
		 Gotoxy(21, 19);
		 cout << "Please press the 'L' key to try again."; 
	}
	 
	 while (username != inputUsername || password != inputPassword)
	 {
	 	 
		 keyPressed = getKeyPress();
		 if (keyPressed == 'L')
		 {
			authorisation(keyPressed, currentMonth, currentYear);
		 }
		 else if (command == command)
		 {
			Gotoxy(16, 18);
			SelectTextColour( clRed);
			cout << "\a";
			cout << "	   " << "The command you entered is invalid." << "	   ";
			Gotoxy(16, 19);
			cout << "	   " << "Please press the 'L' key to login." << "	   ";
		}
	 }	 




}//end of the 'authorisation' function





The modified "authorisation()" function to read the files created by the "createAccount()" function:


void authorisation(int& keyPressed, int& currentMonth, int& currentYear)
{//start of the 'authorisation' function which allows the user to login
	
	int getKeyPress();
	void displayHeaderFooter( int& currentMonth, int& currentYear);
	void displayMenu(int& keyPressed, int& currentMonth, int& currentYear);
	
	CLEAR_SCREEN();

	displayHeaderFooter(currentMonth, currentYear);
	
	ifstream inputFile;
	inputFile.open("userFile", ios::in);
	inputFile >> password;
	Gotoxy(26, 12);
	SelectTextColour( clCyan);
	cout << "Please enter your username.";
		Gotoxy(44, 10);
	cin >> username;
	Gotoxy(26, 13);
	SelectTextColour( clDarkCyan);
		cout << "Please enter your password.";
		Gotoxy(44, 11);
	cin >> password;
	if ( inputFile.fail())
	{
		Gotoxy(23, 18);
		cout << "An error occured whilst trying to login."; 
		Gotoxy(23, 19);
		cout << "Please press 'L' to try again ot 'E' to exit.";
	}
	else
	{
		if ( username == username+".txt"  && password == password)
		{
		Gotoxy(23, 18);
		SelectTextColour( clGreen);
		SelectBackColour( clBlack);
		cout << "You have logged in successfully.";
		Gotoxy(15, 19);
		cout << "Please press the 'M' key to display the Main Menu."; 
				
				keyPressed = getKeyPress();
		if (keyPressed == 'M')
		{
			CLEAR_SCREEN();
			displayHeaderFooter(currentMonth, currentYear);
			displayMenu(keyPressed, currentMonth, currentYear);
		}
		else
		{
			Gotoxy(16, 18);
			SelectTextColour( clRed);
			cout << "\a";
			cout << "The command you entered is invalid.";
			Gotoxy(13, 19);
			cout << "Please press the 'M' key to display the Main Menu.";
		}		

		   }
	
	inputFile.close();
	

}//end of the 'authorisation' function



The modified "authorisation()" function is completely different to the original one now & doesn't have a message if the user enters the wrong password yet (I will do that in a bit) the main thing I am looking for in the modified "authorisation()" function is for the file created in the "createAccount()" function to be read &, if the username & password are the same as what is contained in that file, display the if statement to the user telling them they can procede to the menu.

Again, any help really would be much appreciated & thank you in advance :)

This post has been edited by cJr.: 18 September 2008 - 04:42 PM


Is This A Good Question/Topic? 0
  • +

Replies To: [C++] Reading from a Text File

#2 AmitTheInfinity  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,559
  • Joined: 25-January 07

Re: [C++] Reading from a Text File

Posted 18 September 2008 - 11:40 PM

I haven't looked at your complete code, just modified where I thought it should be different. See if this helps you.

void authorisation(int& keyPressed, int& currentMonth, int& currentYear)
{//start of the 'authorisation' function which allows the user to login
    

    // why these declarations are inside function???

    int getKeyPress();  
    void displayHeaderFooter( int& currentMonth, int& currentYear);
    void displayMenu(int& keyPressed, int& currentMonth, int& currentYear);
    
    CLEAR_SCREEN();

    displayHeaderFooter(currentMonth, currentYear);
    
    ifstream inputFile;   
    Gotoxy(26, 12);
    SelectTextColour( clCyan);
    cout << "Please enter your username.";
        Gotoxy(44, 10);
    cin >> username;
    Gotoxy(26, 13);
    SelectTextColour( clDarkCyan);
        cout << "Please enter your password.";
        Gotoxy(44, 11);
    cin >> passwd;  // you need two different variables to compare so I changed name of one.
    
     inputFile.open(username+".txt", ios::in); // open file AFTER you know which users file should be opened.
    
    if ( inputFile.fail()) // This might happen if file does not exists or it has some problem.
    {
        Gotoxy(23, 18);
        cout << "An error occured whilst trying to login.\n";
        cout << "User may not exists or Login process failed.\n"; // File does not exists then user does not exists.
        Gotoxy(23, 19);
        cout << "Please press 'L' to try again ot 'E' to exit.";
    }
    else
    {
        inputFile >> password;  // It mean user exists so retrieve password from file.
        if ( password == password) // compare passwords
        {
        Gotoxy(23, 18);
        SelectTextColour( clGreen);
        SelectBackColour( clBlack);
        cout << "You have logged in successfully.";
        Gotoxy(15, 19);
        cout << "Please press the 'M' key to display the Main Menu.";
                
                keyPressed = getKeyPress();
        if (keyPressed == 'M')
        {
            CLEAR_SCREEN();
            displayHeaderFooter(currentMonth, currentYear);
            displayMenu(keyPressed, currentMonth, currentYear);
        }
        else
        {
            Gotoxy(16, 18);
            SelectTextColour( clRed);
            cout << "\a";
            cout << "The command you entered is invalid.";
            Gotoxy(13, 19);
            cout << "Please press the 'M' key to display the Main Menu.";
        }        

           }
       else // password does not matched.
       {
          cout << "Wrong Password!.";
          Gotoxy(15, 19);
          cout << "Please press the 'M' key to display the Main Menu.";
       }
    
    inputFile.close();
    

}//end of the 'authorisation' function




I hope this will help you. :)
Was This Post Helpful? 0
  • +
  • -

#3 CalumJR  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 10-May 08

Re: [C++] Reading from a Text File

Posted 19 September 2008 - 05:06 AM

Thank you very much for the reply, I tried all of your code & it gives me just one error.

This line:

inputFile.open(username+".txt", ios::in);


Gives me this error:

"error C2664: 'void std::basic_ifstream<_Elem,_Traits>::open(const wchar_t *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'const wchar_t *'"


I do not understand why?

I have tried other things in it's place such as:

inputFile.open(userFile.c_str(), ios::in);


inputFile.open("userFile", ios::in);



But none of them work. (userFile is declared as a global variable to access username+".txt". Could that be the problem?)
Was This Post Helpful? 0
  • +
  • -

#4 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1382
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Re: [C++] Reading from a Text File

Posted 19 September 2008 - 05:18 AM

Is userFile a string?

Try this:
inputFile.open(userFile.c_str()+".txt");
Was This Post Helpful? 0
  • +
  • -

#5 CalumJR  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 10-May 08

Re: [C++] Reading from a Text File

Posted 19 September 2008 - 05:36 AM

View Postgabehabe, on 19 Sep, 2008 - 01:18 PM, said:

Is userFile a string?

Try this:
inputFile.open(userFile.c_str()+".txt");



Yes userFile is a string, it is declared at the top of the program before the main() function like so:
string userFile = username +".txt";



I have tried what you suggested & get this error:

"error C2110: '+' : cannot add two pointers"

So I messed around with that line & I still can't seem to get it to work. If I put the other lines I suggested in my last post, the program functions without any errors but it doesn't read the userFile.

Could it be because I have declared userFile as a global variable & have not mentioned it anywhere in the authorisation() function?

This post has been edited by cJr.: 19 September 2008 - 05:49 AM

Was This Post Helpful? 0
  • +
  • -

#6 AmitTheInfinity  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,559
  • Joined: 25-January 07

Re: [C++] Reading from a Text File

Posted 19 September 2008 - 05:51 AM

I am not sure why your solutions didn't worked. Anyway, this is the very raw solution at the end. Try this.


char userFile[55];

strcpy(userFile,username.c_str()); //if username is String else no need of c_str if it is char array.
strcat(userFile,".txt");
inputFile.open(userFile, ios::in);



I hope this will help you. :)
Was This Post Helpful? 0
  • +
  • -

#7 CalumJR  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 10-May 08

Re: [C++] Reading from a Text File

Posted 19 September 2008 - 06:57 AM

View PostAmitTheInfinity, on 19 Sep, 2008 - 01:51 PM, said:

I am not sure why your solutions didn't worked. Anyway, this is the very raw solution at the end. Try this.


char userFile[55];

strcpy(userFile,username.c_str()); //if username is String else no need of c_str if it is char array.
strcat(userFile,".txt");
inputFile.open(userFile, ios::in);



I hope this will help you. :)



Thank you, that has helped a lot as it now logs in when the right username is entered. However, the user can enter the right username & any password (not the correct one) & it will still allow them in. I don't understand if I have done the if statement on the password check right. This is my current code as it looks now with the username thing working (obviously I will edit what the text, comments, etc say to fit my program, once the functionality works):


void authorisation(int& keyPressed, int& currentMonth, int& currentYear)
{//start of the 'authorisation' function which allows the user to login
	

	int getKeyPress();  
	void displayHeaderFooter( int& currentMonth, int& currentYear);
	void displayMenu(int& keyPressed, int& currentMonth, int& currentYear);
	
	char passwd;

	CLEAR_SCREEN();

	displayHeaderFooter(currentMonth, currentYear);
	
	ifstream inputFile;   
	Gotoxy(26, 12);
	SelectTextColour( clCyan);
	cout << "Please enter your username.";
	Gotoxy(44, 10);
	cin >> username;
	Gotoxy(26, 13);
	SelectTextColour( clDarkCyan);
	cout << "Please enter your password.";
	Gotoxy(44, 11);
	cin >> passwd;  // you need two different variables to compare so I changed name of one.
	
	 /*inputFile.open(userFile.c_str(), ios::in);*/ // open file AFTER you know which users file should be opened.
   char userFile[55];	
   strcpy(userFile,username.c_str()); //if username is String else no need of c_str if it is char array.  
   strcat(userFile,".txt");  
   inputFile.open(userFile, ios::in);  
	
	if ( inputFile.fail()) // This might happen if file does not exists or it has some problem.
	{
		Gotoxy(23, 18);
		cout << "An error occured whilst trying to login.\n";
		cout << "User may not exists or Login process failed.\n"; // File does not exists then user does not exists.
		Gotoxy(23, 19);
		cout << "Please press 'L' to try again ot 'E' to exit.";
	}
	else
	{
		inputFile >> password;  // It mean user exists so retrieve password from file.
		if ( password == password) // compare passwords
		{
		Gotoxy(23, 18);
		SelectTextColour( clGreen);
		SelectBackColour( clBlack);
		cout << "You have logged in successfully.";
		Gotoxy(15, 19);
		cout << "Please press the 'M' key to display the Main Menu.";
				
				keyPressed = getKeyPress();
		if (keyPressed == 'M')
		{
			CLEAR_SCREEN();
			displayHeaderFooter(currentMonth, currentYear);
			displayMenu(keyPressed, currentMonth, currentYear);
		}
		else
		{
			Gotoxy(16, 18);
			SelectTextColour( clRed);
			cout << "\a";
			cout << "The command you entered is invalid.";
			Gotoxy(13, 19);
			cout << "Please press the 'M' key to display the Main Menu.";
		}		

		   }
	   else // password does not matched.
	   {
		  cout << "Wrong Password!.";
		  Gotoxy(15, 19);
		  cout << "Please press the 'M' key to display the Main Menu.";
	   }
	}
	
	inputFile.close();
	

}//end of the 'authorisation' function




I have tried replacing the if (password == password) code to the variable passwd (e.g. if (password == passwd) & vice-versa, as that is what is being entered, but it gives an error when I do that. This is the error it gives:

"error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::string' (or there is no acceptable conversion) "

I can't seem to understand that & have messed around with it (e.g. trying "=" instead of "==" knowing it wouldn't work anyway).

Do you have any ideas please? You have been a great help so far, thank you.

----------------
Now playing on iTunes: The Killers - Read My Mind [Like Rebel Diamonds Mix]
via FoxyTunes

This post has been edited by cJr.: 19 September 2008 - 07:07 AM

Was This Post Helpful? 0
  • +
  • -

#8 gabehabe  Icon User is offline

  • GabehabeSwamp
  • member icon




Reputation: 1382
  • View blog
  • Posts: 10,962
  • Joined: 06-February 08

Re: [C++] Reading from a Text File

Posted 19 September 2008 - 07:05 AM

That's because of this line:
if (password == password)
It will always be true, since password is equal to itself (obviously)

Did you mean if (password == "password") or something similar?

Other than that, passwd is stored as a char, while password is stored as a string.

Try changing char passwd to string passwd

Note: The error means that you are checking a string against something that isn't a string. You either need to check it against a string, or cast one of them so they are the same datatype. :)
Was This Post Helpful? 0
  • +
  • -

#9 AmitTheInfinity  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,559
  • Joined: 25-January 07

Re: [C++] Reading from a Text File

Posted 19 September 2008 - 08:19 AM

See my comments inside code.

void authorisation(int& keyPressed, int& currentMonth, int& currentYear)
{//start of the 'authorisation' function which allows the user to login
    
    // Still can't understand why these function declarations are inside?

    int getKeyPress();  
    void displayHeaderFooter( int& currentMonth, int& currentYear);
    void displayMenu(int& keyPressed, int& currentMonth, int& currentYear);
    
    char passwd[100]; // This has to be either string or character array.
    int passwdNotMatched = 1;  // While loop will continue until you enter a valid password.
    char cmd; // You are showing message to accept command but not accepting it from user.

    CLEAR_SCREEN();

    displayHeaderFooter(currentMonth, currentYear);
    
    ifstream inputFile;  
 
    while(passwdNotMatched) // This will continue till you give correct username and password or exit command.
    {
    Gotoxy(26, 12);
    SelectTextColour( clCyan);
    cout << "Please enter your username.";
    Gotoxy(44, 10);
    cin >> username;
    Gotoxy(26, 13);
    SelectTextColour( clDarkCyan);
    cout << "Please enter your password.";
    Gotoxy(44, 11);
    cin >> passwd;  // you need two different variables to compare so I changed name of one.
    
     /*inputFile.open(userFile.c_str(), ios::in);*/ // open file AFTER you know which users file should be opened.
   char userFile[55];    
   strcpy(userFile,username.c_str()); //if username is String else no need of c_str if it is char array.  
   strcat(userFile,".txt");  
   inputFile.open(userFile, ios::in);  
    
    if ( inputFile.fail()) // This might happen if file does not exists or it has some problem.
    {
        Gotoxy(23, 18);
        cout << "An error occured whilst trying to login.\n";
        cout << "User may not exists or Login process failed.\n"; // File does not exists then user does not exists.
        Gotoxy(23, 19);
        cout << "Please press 'L' to try again or 'E' to exit.";
        keyPressed = getKeyPress();
        if(keyPressed == 'E' || keyPressed == 'e') // Return to main function.  You may even exit from here.
           return;
    }
    else
    {
        inputFile >> password;  // It mean user exists so retrieve password from file.
        inputFile.close();
        if ( password.compare(passwd) == 0) // compare passwords
        {
        passwdNotMatched = 0;
        Gotoxy(23, 18);
        SelectTextColour( clGreen);
        SelectBackColour( clBlack);
        cout << "You have logged in successfully.";
        Gotoxy(15, 19);
        cout << "Please press the 'M' key to display the Main Menu.";
                
                keyPressed = getKeyPress();
        if (keyPressed == 'M')
        {
            CLEAR_SCREEN();
            displayHeaderFooter(currentMonth, currentYear);
            displayMenu(keyPressed, currentMonth, currentYear);
        }
        else
        {
            Gotoxy(16, 18);
            SelectTextColour( clRed);
            cout << "\a";
            cout << "The command you entered is invalid.";
            Gotoxy(13, 19);
            cout << "Please press the 'M' key to display the Main Menu.";            
        }        

           }
       else // password does not matched.
       {
          cout << "Wrong Password!.";
          passwdNotMatched = 1;
          cout << "Please press 'L' to try again or 'E' to exit.";
          keyPressed = getKeyPress();
            if(keyPressed == 'E' || keyPressed == 'e') // Return to main function.  You may even exit from here.
              return;
          
       }
    }
    }
    

    

}//end of the 'authorisation' function



I hope this will help you.
Was This Post Helpful? 0
  • +
  • -

#10 CalumJR  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 49
  • Joined: 10-May 08

Re: [C++] Reading from a Text File

Posted 19 September 2008 - 02:30 PM

Thank you very much to both AmitTheInfinity & gabehabe, you have both helped me immensely & I am extremely grateful.

I used gabehabe's suggestion of just changing the variable declaration to 'string' rather than 'char' earlier on & it's worked perfectly so far, I have just been tidying up my code & making sure it all works fully & seamlessly, with no bugs (currently my createaccount() function will not work properly but I'm sure it will be easy for me to sort that out when I am back from work later tonight).

I will look at your latest suggestion, AmitTheInfinity, after work as it is bound to help my knowledge even more & then I will post the final working code later tonight (& also, AmitTheInfinity, I will explain why I have declared certain functions in the authorisation() function ;))

----------------
Now playing on iTunes: Flo Rida - Low (Feat. T-Pain)
via FoxyTunes
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1