title: C++: Reading from file /UserName and Password
body: <p>I am doing a program that will prompt a user to login in using their username and password. I have a textfile(userandpassword.txt) that contains a list of username and password. so what happens is, the user input their username and password, and their input will be matched with the username and password in the textfile. if it matches, they can login and if it doesn't match, it will print out "Invalid username or password". below is what I have.</p>
  
  <p>textfile(userandpassword.txt)</p>
  
  <pre><code>john abcd
  mary efgh
  jane ijkl
  </code></pre>
  
  <p>my codes</p>
  
  <pre><code>string line = " ";
  ifstream readFile("userandpassword.txt");
  string UserName;
  string Password;
  string _UserName;
  string _Password;
  
  cout &lt;&lt; "Enter UserName: ";
  cin &gt;&gt; UserName;
  
  cout &lt;&lt; "Enter Password: ";
  cin &gt;&gt; Password;
  
  while (getline(readFile,line)) {
  
      stringstream iss(line);
      iss &gt;&gt; _UserName &gt;&gt; _Password;
  
      if (UserName == _UserName &amp;&amp; Password == _Password) {
          cout &lt;&lt; "Login Successfully!"&lt;&lt; endl;
      }
  
      else {
          cout &lt;&lt; "InValid UserName And Password"&lt;&lt; endl;
      }
  
  }
  </code></pre>
  
  <p>The problem is if I key in username: john and password: abcd it will return me the output as shown below</p>
  
  <pre><code>Login Successfully!
  InValid UserName And Password
  InValid UserName And Password 
  </code></pre>
  
  <p>whereas if I key in username: mary and password: efgh it will return me the out as shown below</p>
  
  <pre><code>InValid UserName And Password
  Login Successfully!
  InValid UserName And Password
  </code></pre>
  
  <p>and finally username: jane and password: ijkl</p>
  
  <pre><code>InValid UserName And Password
  InValid UserName And Password
  Login Successfully!
  </code></pre>
  
  <p>but this is not the result I wanted, what I wanted is it reads through the file line by line for the username and password and if matches with the user's input , It will just output "Login Successfully" and same goes for if it does not match , it will just print out "Invalid Username and password".  </p>
  
  <p>e.g</p>
  
  <p>if I key in username: mary and password: efgh, my expected output</p>
  
  <pre><code>Login Successfully!
  </code></pre>
  
  <p>and if I key in any invalid username and password , my expected output</p>
  
  <pre><code>Invalid Username and password.
  </code></pre>
  
  <p>Any ideas or suggestions on how should I achieve my expected output? Thanks</p>