Reputation: 1594
I wrote a program that basically reads 2 lines from a text file saved in the main project file. It's notable that my OS is Windows. I need to read only specific parts of text from the first and 2nd line. For example I have one text file which has 2 lines: User: Administrator and password: stefan. Within my program I'm asking the user for the username and the password, and checks if it matches the one in the text file, however the lines contain some unnecessary strings: "User:" and "Password:". Is there any way to read everything but exclude the unnecessary letters? This is the code I'm using to read from file:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream myfile("Hello.txt");
string str, str2;
getline (myfile, str);
getline(myfile, str2);
return 0;
}
Where str is the first line from the text file and str2 is the 2nd.
Upvotes: 0
Views: 4484
Reputation: 8587
This code loads the user and password from a file named user.txt
.
Contents of file:
user john_doe
password disneyland
It reads a line using getline( myfile, line )
, splits the line using istringstream iss(line)
and stores the user and password in separate strings.
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string s_userName;
string s_password ;
string line,temp;
ifstream myfile("c:\\user.txt");
// read line from file
getline( myfile, line );
// split string and store user in s_username
istringstream iss(line);
iss >> temp;
iss >> s_userName;
// read line from file
getline( myfile, line );
// split string and store password in s_password
istringstream iss2(line);
iss2 >> temp;
iss2 >> s_password;
//display
cout << "User : " << s_userName << " \n";
cout << "Password : " << s_password << " \n";
cout << " \n";
myfile.close();
return 0;
}
Upvotes: 3