Run the code below and ask the following guestions: 1. What does the program do?
ID: 3635900 • Letter: R
Question
Run the code below and ask the following guestions:1. What does the program do?
2. Where is "login.txt" file located?
3. Which lines open the the file for writing?
4. Which lines open the the file for reading?
5. Which lines closes the file?
6. What does the code "inFile.eof()" do?
int main()
{
ofstream outFile;
outFile.open("login.txt", ios::app);
string username = "";
string password = "";
char answer;
if (outFile.is_open())
{
do
{
cout << "Enter username: " << endl;
cin >> username;
cout << "Enter password: " << endl;
cin >> password;
outFile << username << " " << password << endl;
cout << "Enter another username/password? Y or N" << endl;
cin >> answer;
}while(answer == 'Y');
outFile.close();
}
else
cout << "The file could not be opened" << endl;
cin.ignore(100, ' ');
ifstream inFile;
inFile.open("login.txt", ios::in);
string uname = "";
string pword = "";
bool found = false;
if (inFile.is_open())
{
cout << "Enter your username: " << endl;
getline(cin, username);
cout << "Enter your password: " << endl;
getline(cin, password);
while(!inFile.eof())
{
getline(inFile, uname, ' ');
getline(inFile, pword);
if (uname == username && pword == password)
{
found = true;
break;
}
}
inFile.close();
}
else
cout << "The file could not be opened" << endl;
if (found)
cout << "Login was OK" << endl;
else
cout << "Login failed" << endl;
}
Explanation / Answer
1.Ans
The program opens a text file called login.txt in append mode
and ask the user for user name and password and writes to file
login.txt and close the file.and again the program login.txt is opened in read mode (ios::in) and the user name and password
and if the user name and password matches then displays a message
that login ok else Login failed.
2.Ans
The file login.txt is creted in current working directory if you are working
with TURBO CPP.or else the file login.txt is created in debug folder if you are
working visual studio 2010 vc++
3.Ans
Lines for writing into file login.txt is
outFile << username << " " << password << endl;
4.Ans
Lines reading from file login.txt is
getline(inFile, uname, ' ');
getline(inFile, pword);
5.Ans
Lines closes the file are
This line closes the outFile stream object
outFile.close();
This line closes the inFile stream object
inFile.close();
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.