0

For some reason, no matter what text I write as input, the program will always return Succes, even if it's not in the .txt with the list of users,each separated by '\n'

My main issue is the " char b[20]; strcpy(b,inputUser); " line. If I comment it, the program will printf the inputUser badly, even thought that line has NOTHING to do with the rest of the code (was planning to use it to cut the '\n' from the userinput)

#include <iostream>
#include <cstring>
#include <string>
#include <fstream>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main()
{
    bool found=0;
    int txtFD=open("users.txt",O_RDONLY);

    char letter[2]; strcpy(letter,"");
    char user[20]; strcpy(user,"");
    char inputUser[20]; strcpy(inputUser,"");

    read(0, inputUser,20);
    char b[20]; strcpy(b,inputUser);

    while( read(txtFD, letter, 1) && found==0 )
    {

        if(letter[0] == '\n')   //am citit un user intreg, vad daca asta e
        {
            strcat(user,letter);
            if( strstr(inputUser, user) == 0 )
            {
                cout<<"am gasit "<< inputUser <<" in lista.\n";
                found=1;
            }
            strcpy(user,"");
        }
        else
        strcat(user,letter);

    }

    if(found)
        cout<<"Succes!\n";
    else cout<<"Failure!\n";


}
Andy
  • 141
  • 3
  • 13
  • `letter` is supposed to be a C string (0-terminated) and you set its first character before using it to `strcat` at the end of the input. You never set the terminating 0 though. Does your compiler do that? Best make sure. (You'll also be interested to learn that there are functions to read entire lines. And try a debugger.) – Jongware Dec 17 '17 at 15:26
  • 2
    [That's bad c++ code](https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr). – user0042 Dec 17 '17 at 15:27
  • 2
    `std::string` is your friend. – Alan Stokes Dec 17 '17 at 15:48
  • 1
    C with cout, the problems follow. –  Dec 17 '17 at 15:52
  • Omg pls have a look at [how to read a file line-by-line](https://stackoverflow.com/questions/7868936/read-file-line-by-line). – rustyx Dec 17 '17 at 16:47

0 Answers0