Hi,

I need a program to search all lines of a file (a whole file) for a certain string. In my concrete case, I need it for login. Let me sum all of this up, so you get the whole overall point of what I have so far:
- a user enters a username (inputUsername) and a password (inputPassword)and these 2 strings are connected into a new string: userAndPass
- the file which contains multiple lines of [username] [password] patterns is opened and searched
- when the line with the entered [username] [password] is found, which is practically equal to userAndPass string, the user is forwarded to the main menu.

Here's the code of the Login.h header file.
`Inline Code Example Here

   #pragma once
    #include <iostream>
    #include <conio.h>
    #include <fstream>
    #include <string>
    #include <iosfwd>
    #include <iterator>
    #include <algorithm>
    #include "Lek.h"
    using namespace std;

    class Login
    {

    public:
        string username, password;
        string inuser, inpass;

        char opcija;
        ofstream usersFile;

        string inputUsername;
        string inputPassword;
        Lek lek1;


            // User registration
            void userRegisterDo()
            {

                if (    !usersFile.is_open())
                {
                    usersFile.open("userData.txt");
                }

                usersFile << username << " " << password << endl;

                usersFile.close();
            }

            // Initialize user registration
            void userRegister()
            {
                cout << "Dobrodosli!\n-------------------------\n\nMolimo registrujte se.\nUnesite novi username:\n";
                cin >> username;

                cout << "\nUnesite novi password:\n";
                cin >> password;

                userRegisterDo();
            }

            // User login function
            void login()
            {
                cout << "Username:\n";
                cin >> inputUsername;

                cout << "\nPassword:\n";
                cin >> inputPassword;

                string userAndPass = inputUsername + " " + inputPassword; // Ono sto se trazi
                int offset; 
                string line;
                ifstream usersFile;
                usersFile.open ("userData.txt");

                if(usersFile.is_open())
                {
                    while(!usersFile.eof())
                    {
                        istream_iterator<char> eof;
                        getline(usersFile,line);
                        if (eof == search(istreambuf_iterator<char>(usersFile), eof, userAndPass.begin(), userAndPass.end())) {    // ako je pronadjen login
                            // Autentikacija je uspela
                            system("cls");
                            // Meni aplikacije
                            do 
                            {
                                cout << endl;  
                                cout << "Dobrodosli. Odaberite opciju:\n"
                                    << "1. Provera starosti leka\n"
                                    << "2. Unos novog leka\n"
                                    << "3. Brisanje leka\n"
                                    << "4. Pregled lekova\n"
                                    << "5. Izlaz"
                                    << endl << endl;

                                cin >> opcija;

                                cout << endl;

                                switch (opcija)
                                {
                                case '1':
                                    system("cls");
                                    lek1.unosDatumaProizvodnje();
                                    lek1.starostLeka();
                                    lek1.prikazStarostiLeka();
                                    break;

                                case '2':
                                    system("cls");
                                    lek1.unosLeka();
                                    system("cls");
                                    break;

                                case '3':
                                    system("cls");
                                    lek1.brisanjeLeka();
                                    getch();
                                    system("cls");
                                    break;

                                case '4':
                                    lek1.pregledLekova();
                                    cout << endl << "Kraj fajla.\n";
                                    getch();
                                    system("cls");
                                    break;

                                case '5':
                                    exit(1);
                                    break;

                                default:
                                    cout << endl;
                                    system("cls");
                                    cout << "Uneli ste pogresnu opciju. Pokusajte ponovo!\n";
                                    cout << endl;
                                    break;
                                }
                            } while (opcija != '5');
                        }

                        else    // ako login nije pronadjen
                        {
                            cout << "\nUsername i/ili sifra nisu dobri!\n\n\n\n";
                            login();
                        }
                    }

                    usersFile.close();
                }
                else
                    cout << "Fajl userData.txt se ne moze otvoriti." << endl;


            long begin, end;

            if (usersFile.good())
            {
                cout << "userData.txt pronadjen!\n\n";
            }

            else {
            userRegister();
            }

            if (usersFile.is_open())
            {
                begin = usersFile.tellg();
                usersFile.seekg (0, ios::end);

                end = usersFile.tellg();
                usersFile.close();

                if (begin == end)
                {
                    userRegister();
                }

                else
                {
                    login();
                }
            }

            getch();
        }


    };

I didn't post any other files here, because they're not directly related to the problem I have.

The error I receive after compiling the code is:

Output from Build

1>------ Build started: Project: IT320 Pharmacy, Configuration: Debug Win32 ------
1>Build started 22-Jun-12 21:50:38.
1>InitializeBuildStatus:
1>  Touching "Debug\IT320 Pharmacy.unsuccessfulbuild".
1>ClCompile:
1>  Main.cpp
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(63): warning C4996: 'localtime': This function or variable may be unsafe. Consider using localtime_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\time.inl(112) : see declaration of 'localtime'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(148): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(155): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(168): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(175): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(188): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(195): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(205): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(214): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(224): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(237): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(263): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(281): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(295): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(308): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\lek.h(313): warning C4996: 'getch': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _getch. See online help for details.
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\conio.h(128) : see declaration of 'getch'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\login.h(74): error C2780: '_FwdIt1 std::search(_FwdIt1,_FwdIt1,_FwdIt2,_FwdIt2,_Pr)' : expects 5 arguments - 4 provided
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(621) : see declaration of 'std::search'
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\login.h(74): error C2782: '_FwdIt1 std::search(_FwdIt1,_FwdIt1,_FwdIt2,_FwdIt2)' : template parameter '_FwdIt1' is ambiguous
1>          c:\program files (x86)\microsoft visual studio 10.0\vc\include\algorithm(581) : see declaration of 'std::search'
1>          could be 'std::istream_iterator<_Ty>'
1>          with
1>          [
1>              _Ty=char
1>          ]
1>          or       'std::istreambuf_iterator<_Elem,_Traits>'
1>          with
1>          [
1>              _Elem=char,
1>              _Traits=std::char_traits<char>
1>          ]
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\login.h(162): warning C4244: '=' : conversion from 'std::streamoff' to 'long', possible loss of data
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\login.h(165): warning C4244: '=' : conversion from 'std::streamoff' to 'long', possible loss of data
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\program.h(37): warning C4244: '=' : conversion from 'std::streamoff' to 'long', possible loss of data
1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\program.h(40): warning C4244: '=' : conversion from 'std::streamoff' to 'long', possible loss of data
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:00.72
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

These two lines are colored red:

1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\login.h(74): error C2780: '_FwdIt1 std::search(_FwdIt1,_FwdIt1,_FwdIt2,_FwdIt2,_Pr)' : expects 5 arguments - 4 provided

1>c:\users\boris\documents\visual studio 2010\projects\it320 pharmacy\it320 pharmacy\login.h(74): error C2782: '_FwdIt1 std::search(_FwdIt1,_FwdIt1,_FwdIt2,_FwdIt2)' : template parameter '_FwdIt1' is ambiguous

Do you have any idea about how to solve these issues? Thanks in advance. If you need any more code or info, tell me.

Recommended Answers

All 8 Replies

This is a program I did for another topic from the C department, maybe this will help you. Note that it's done in C, but the ideea matters.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int line_num(char *filename){
    FILE *f;
    char c;
    int lines = 0;
    f = fopen(filename, "r");
    if(f == NULL) return (0);
    while((c = fgetc(f)) != EOF)
        if(c == '\n') lines++;
    fclose(f);
    if(c != '\n') lines++;
    return (lines);
}

int main(){
    FILE *f_text , *f_pattern;
    int found, text_ln=line_num("text.txt");
    f_text = fopen("text.txt", "r");
    fseek(f_text, 0, SEEK_END);
    int text_file_size = ftell(f_text);
    fclose(f_text);

    f_text = fopen("text.txt", "r");
    char *text;
    text = (char*)malloc (text_file_size+1);
    text[text_file_size]='\0';

    f_pattern = fopen ( "pattern.txt" , "r");
    fseek (f_pattern,0, SEEK_END);
    int pattern_file_size = ftell (f_pattern);
    fclose(f_pattern);

    f_pattern = fopen ( "pattern.txt" , "r");
    char *pattern;
    pattern = (char*)malloc (pattern_file_size+1);
    pattern[pattern_file_size]=0;
    if(f_pattern!= NULL){
        fgets(pattern, sizeof(char)+pattern_file_size, f_pattern);
    }
    int i, j, k;
    if(f_text != NULL && f_pattern!=NULL){
        for (;text_ln--;){
            fgets(text, sizeof(char)+text_file_size,f_text);
            for (i=0;i<text_file_size;i++){
                if (pattern[0]==text[i]){
                    k=i;
                    for (j=0;j<pattern_file_size;j++){
                        if (pattern[j]==text[k]){
                            k++;
                            if (j+1==pattern_file_size) found=1;
                        }
                        else break;
                    }
                }
            }
        }
    }
    fclose(f_text);
    fclose(f_pattern);

    if(found==1) printf ("The pattern was found.\n");
    else printf("The pattern wasn't found.\n");

    free (text);
    free (pattern);
    return (0);
}

and here's the revised code from above in C++:

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;

int main(){
    string file, pattern, line;
    int found, k, psize;
    cout<<"File: ";
    cin>>file;
    cout<<"Pattern: ";
    cin>>pattern;
    psize=pattern.size();
    ifstream text(file.c_str(), ios::in);
    if(text){
        while (getline(text, line)){
            for (int i=0;i<(int)line.size();i++){
                if (pattern[0]==line[i]){
                    k=i;
                    for (int j=0;j<psize;j++){
                        if (pattern[j]==line[k]){
                            k++;
                            if (j+1==psize) found=1;
                        }
                        else break;
                    }
                }
            }
        }
    }
    if(found==1) cout<<"The pattern was found.\n";
    else cout<<"The pattern wasn't found.\n";
    return (0);
}

It's just that it's kinda hard for me to understand exactly the menu's functions.
And regarding your errors:

expects 5 arguments - 4 provided

That means that you call a function with less parameters.
And:

template parameter '_FwdIt1' is ambiguous

it sais that's unclear for the compiler that templates' argument, thou I don't see in your program that you use that.

Thanks, but can you tell me how to write a code which will search the whole file for the entered username and password, separated by space (search all lines)?

Example:
Username:
user1

Password:
pass1

Now, if a program finds a line which contains this line: user1 pass1, then it does one thing, and if not, it does another (like inform a user it found a line, etc.). I seem to have a lot of trouble with these stuff. I'll then implement this into my app.

Thanks for help.

Well, take for example the code in C++. As a pattern, you put in the username and the passowrd, and if it's found it will output that the pattern was found, else it will output that the pattern wasn't found.

std:: string together, user, pass;
std::cout<<"Username: ";
std::cin>>user;
std::cout<<"Password: ";
std::cin>>pass;
together=user+pass;//or user+" "+pass;

than you set the pattern to the together string.

cout<<"Pattern: "; //you delete 
cin>>pattern;      //these lines

//and replace them with:

pattern=together;

Thanks, but looks like I have the same problem as before. I'm still using your code, but it keeps telling me that it found the string, even if I partially enter it (for example: user1 pas is found, because it's a substring of user1 pass1).
Any ideas about forcing the app to look for the whole string, and not a substring?

And yeah, it also exits if I enter a username and password from the second or other lines. It only looks for the first line in the file.

And yeah, it also exits if I enter a username and password from the second or other lines. It only looks for the first line in the file.

i doubt that, because i tested on my pc, and on a file text with multiple lines, where the pattern was at the very end of the file, it printed ok.
About the whole string, I don't know where's the problem:

#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
using namespace std;

bool search(string file,string pattern){
    string line;
    int k, psize, lsize;
    psize=pattern.size();
    ifstream text(file.c_str(), ios::in);
    if(text){
        while (getline(text, line)){
            lsize=line.size();
            for (int i=0;i<lsize;i++){
                if (pattern[0]==line[i]){
                    k=i;
                    for (int j=0;j<psize;j++){
                        if (pattern[j]==line[k]){
                            k++;
                            if (j+1==psize) return (true);
                        }
                        else break;
                    }
                }
            }
        }
    }
    return (false);
}

int main(){
    string file="pas.txt", pattern, user, password;
    for (int i=0;i<5;i++){
        cout<<"Username: ";
        cin>>user;
        cout<<"Password: ";
        cin>>password;
        pattern=user+password;
        if (search(file,pattern)) cout<<"Ok, I have found you.\n";
        else cout<<"Invalid user/password.\n";
    }
    return (0);
}

I have this output:

Username: laie1268
Password: 123
Ok, I have found you.
Username: laie1268
Password: 456
Invalid user/password.
Username: laie1270
Password: 789
Ok, I have found you.
Username: laie1270
Password: 678
Invalid user/password.
Username: laie1269
Password: 456
Ok, I have found you.

//and the text file pas.txt looks like this: 
laie1268123 laie1269456 laie1270789
// and tested with single line user+pass like this:
laie1268123
laie1269456
laie1270789

So then the problem lies somewhere else than my code.

If your compiler is up to date, it will support regular expressions (#include <regex>), which means you can do something like this:

regex userName("someString");
regex passWord("someOtherString");

while ( //loop over whole file, reading in two lines at a time and sticking them in stringFromFile)
{
  if (regex_search(stringFromFile.begin(), stringFromFile.end(), userName))
  {
     // found userName in this string
      if (regex_search(stringFromFile.begin(), stringFromFile.end(), passWord))
      {
        // and found the password in the same string
        // Do something
      }
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.