PewK
PewK

Reputation: 397

C++ Reading a SPECIFIC line from a text file and comparing it with an input

I'm building a login function where the user enters a username. The program should be able to read a text file called "accounts.txt" and read the username line (Which is the 4th line in the text file) and compare the input with the text file's username.

  1. User enters username
  2. Program reads the 4th line of the text file (i.e: username)
  3. Checks if both usernames are the same
  4. Success message

How do I get this done, mates?

P.S: fstream is used in this, am I right?

Upvotes: 0

Views: 11264

Answers (1)

Agentlien
Agentlien

Reputation: 5126

The easiest way to do this is simply to read each line, and only process the ones you are interested about:

std::string line;
ifstream login("accounts.txt");
for(int i = 0; i < desired_line; ++i)
   getline(login, line)
getline(login, line);
use_input(line);

Update: If the line contains (or begins with) a single integer which represents the id, you can convert it to an integer as such:

std::stringstream stream(line);
int id;
stream>>id;

Upvotes: 0

Related Questions