Reading from txt files and making it strings.
Mar 10, 2015 at 7:23am UTC
Example if I have a Sample.txt and it contains.
Hello
Hi
How could i choose Hi and put it in a String Variable?
Mar 10, 2015 at 8:03am UTC
Mar 10, 2015 at 8:58am UTC
I'm a beginner sorry, I don't seem to understand the getline part for the ifstream. When I code I cannot get my text file contain and place it in a String Variable.
There are two words in the text file:
Hi
Hello
I would like to put Hi in Username. How? (Sorry I'm a noob here)
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
string loadfile, username, password, Username, Password;
cout << "Please put account name: " << endl;
cin >> loadfile;
cout << endl;
ifstream accntNme(loadfile.c_str());
if (accntNme.is_open())
{
username = Username;
password = password;
cout << "Username: " << endl;
cin >> Username;
cout << "Password: " << endl;
cin >> Password;
if (username == Username && password == Password)
{
cout << "Welcome " << Username << "!" << endl;
}
else
{
cout << "Wrong Username/Password." << endl;
}
}
Mar 10, 2015 at 9:16am UTC
input.txt :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <fstream>
using namespace std;
int main(){
string s;
ifstream in("input.txt" );
in >> s;
cout << "s = " << s << endl;
in >> s;
cout << "s = " << s << endl;
return 0;
}
output:
Mar 10, 2015 at 9:16am UTC
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
#include <iostream>
#include <fstream>
#include <string>
int main()
{
// read username and password entered by the user
std::string user_name ;
std::cout << "user name? " ;
std::cin >> user_name ;
std::string password ;
std::cout << "password? " ;
std::cin >> password ;
const char * const path_to_password_file = "pword.txt" ;
std::ifstream file(path_to_password_file) ; // open the file for input
std::string user_name_in_file ;
std::string password_in_file ;
file >> user_name_in_file >> password_in_file ; // read username and password in file
if ( user_name == user_name_in_file && password == password_in_file ) // check if they match
{
std::cout << "welcome!\n" ;
// ...
}
else
{
// login error
}
}
Mar 10, 2015 at 9:52am UTC
Thank you guys for the help, I was able to fix it!
Topic archived. No new replies allowed.