program can't read data from text file... solution?

Jul 27, 2016 at 7:59am
hi,

I got a problem in writing code for login function of my program.

I wanted to make program check user id and password from plain text file(user.txt)

1.file have data as follows(id, password are "string")
id pwd
==== =====
zack greinke
louis lenox
robin williams
alex cardo
ugolino grimaldi

2. code
- header file
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#ifndef PRAC1_H
#define PRAC1_H

#include <iostream>
#include <vector>
#include <fstream>
#include <memory>
#include <string>


using namespace std;

struct user
{
	string id;//user id
	string pwd;//user password
};

const char* userDB = "user.txt";

bool isExist(const char* f)
{
	fstream in;
	in.open(f, ios::in | ios::binary);

	if (in.fail())
		return true;
	else
		return false;
	in.close();
}

void save(bool c, const char* f,string i,string p)
{
	fstream o;

	if (c == true)
	{
		o.open(f, ios::out | ios::binary);
	}
	else
	{
		o.open(f, ios::out | ios::app | ios::binary);
	}
	o << i << " " << p << endl;
	o.close();
}

#endif 


- main function
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "Prac1.h"

int main(void)
{
	user* u = new user();
	string id, pwd;
	vector<user> v;//vector has "user"data type

	fstream in;
	in.open(userDB, ios::in | ios::binary);

	while (in>>u->id>>u->pwd)
	{
		v.push_back(*u);
	}

	cout << "id:";
	cin >> id;

	user* veri = new user();

	for (auto it = begin(v); it < end(v); it++)
	{
		if (it->id == id)
		{
			veri->id = it->id;
			veri->pwd = it->pwd;
		}
		else
		{
			cout << "error!" << endl;
		}
	}

	cout << "pwd:";
	cin >> pwd;

	if (veri->pwd == pwd)
	{
		cout << veri->id << " " << veri->pwd << endl;
		cout << "verified!" << endl;
	}
	

	
	
	system("pause");
	return 0;
}


i tested above code but result wasn't not good.
ID: louis
pwd:*****(lenox)
incorrect id!

I couldn't figure out why. If someone pick error or fault of my code, I would appreciate it.

Last edited on Jul 27, 2016 at 7:59am
Jul 27, 2016 at 3:05pm
Why all the pointers? Why not just use "normal" non-pointer instances?

If someone pick error or fault of my code

Probably because you always read to the end of the file when trying to verify the items.

By the way why are you using binary mode?

You really should avoid putting executable code inside a header, and never use the using namespace std; clause in the global scope of a header file.

Topic archived. No new replies allowed.