r/learnprogramming • • 2d ago

hi, i started learning cpp by myself since about 2 weeks ago, and i wrote my first useful simple program. the thing is that cause i learn by myself i don't know where my level is, so i wrote this program as a hope someone can judge me based on the simple first program i wrote.

/*
i learned file reading and writing
data types like int, strings
data saving, declaration, initializing, and defining
arrays and vectors
integrating vectors and file reading and writing
enums and the enum class
functions
calling functions and etc

so basically, this simple program asks you to write a password and a username and points you want to save
then it will save them in a text file called "users"
then it will ask you to write the pasword and username
then it will dispaly a comment depending on your points count
and if you run the program again and wrote a new saved password and username, then used the old passwerd and username, it will judge you based on that

and thanks!!
*/

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
struct user {
std::string username;
std::string password;
int points;
};

enum class Ranking {
Trash,
Intermediate,
Advanced,
Legendary,
Mr_VIP
};

Ranking getrank(int points)
{
if (points < 250) return Ranking::Trash;
if (points < 500) return Ranking::Intermediate;
if (points < 750) return Ranking::Advanced;
if (points < 1000) return Ranking::Legendary;
return Ranking::Mr_VIP;
}

void addUser(std::string username, std::string password, int points)
{
std::ofstream file("users.txt", std::ios::app);
file << username << " ";
file << password  << " ";
file << points << " " << "\n";
}

std::vector<user> loadUsers()
{
std::vector<user> users;
std::ifstream file("users.txt");
user u;
while (file >> u.username >> u.password >> u.points)
{
users.push_back(u);
}
return users;
}

int main()
{
std::string savedUser;
std::string savedPass;
int savedPoints;

std::cout << "Enter the username you wanna save: ";
std::cin >> savedUser;
std::cout << "\n";

std::cout << "Enter the password you wanna save: ";
std::cin >> savedPass;
std::cout << "\n";

std::cout << "Enter the points you wanna save: ";
std::cin >> savedPoints;
std::cout << "\n";
if (std::cin.fail() || savedPoints < 0)
{
std::cout << "Error!!!\n";
return 0;
}

user u;
u.username = savedUser;
u.password = savedPass;
u.points = savedPoints;

system("cls");

addUser(savedUser, savedPass, savedPoints);

std::vector<user> users = loadUsers();

for (int attempt = 0; attempt < 3; attempt++)
{
std::string iusername;
std::string ipassword;
std::cout << "Enter your username: ";
std::cin >> iusername;
std::cout << "\n";
std::cout << "Enter your password: ";
std::cin >> ipassword;
std::cout << "\n";

bool found = false;
int foundPoints = 0;

for (const user& u : users)
{
if (u.username == iusername && u.password == ipassword)
{
found = true;
foundPoints = u.points;
break;
}
}

if (found)
{
std::cout << "logged in successfully!\n\n";

Ranking rank = getrank(foundPoints);

switch (rank)
{
case Ranking::Trash:
std::cout << "You are trash\n";
break;
case Ranking::Intermediate:
std::cout << "You are intermediate\n";
break;
case Ranking::Advanced:
std::cout << "You are advanced\n";
break;
case Ranking::Legendary:
std::cout << "You are legendary\n";
break;
case Ranking::Mr_VIP:
std::cout << "You are Mr. VIP\n";
break;
}
return 0;
}
else
{
std::cout << "wrong password or username, try again\n\n";
}
}

std::cout << "too many failed attempts!!!\n";
return 0;
}
20 Upvotes

35 comments sorted by

11

u/SharkSymphony 1d ago edited 1d ago

This code has a very low level of abstraction and reusability, and inconsistent style. Storing a password as plaintext in a file is also terrible practice from a security perspective, and repeatedly opening and appending a file is not a great way of managing a database. Space as a field separator in your file will only work if your input cannot contain spaces, and the program in general seems to be a contrived demo. Given these, I would rate it as beginner code. The user struct is a nice start though, and you should never discount the accomplishment of nontrivial code that works!

You should be capable of taking everything repeated in your code and devising functions (or member functions of, say, `user`) that you repeatedly call. As more advanced topics, I think it would also be good to give some thought as to how you would handle passwords securely, and what you could deploy to take your database to the next level, though this approach is giving you some experience with the C++ I/O library so it's not wasted effort.

Good hunting!

2

u/Born_Juggernaut_346 1d ago

I really appreciate it that you pinpointed the terrible things, I mean it's not a demo, I gave it everything I had, but I will try to improve. Thanks for that!

3

u/dkopgerpgdolfg 1d ago

In addition to the points made my the previous commenter, I'd like to point out: Error handling. Can't get started early enough with that. Pretty much everything can fail, and most of it you just ignore.

(and while there are many other possible topics and tips to learn/give, that can wait until you got more used to the current things)

2

u/Born_Juggernaut_346 1d ago

Oh, while I was trying to correct the bugs within this (humbly simple) code, it had me stressing all day trying to understand what was the problem. Thanks for pointing out that. And to be honest, while I was writing it I felt like I was the best in the world when it succeeded 😌

2

u/SharkSymphony 1d ago

That feeling never gets old. 😁

3

u/SharkSymphony 1d ago

Demo not in the sense that it's terrible but in the sense that it does one specific, preprogrammed thing: enter and store one user, then try to log in against that user and use what you just entered, then exit.

26

u/dkopgerpgdolfg 1d ago

After two weeks, you're a beginner. I know that without looking at the code at all. And it will stay true for long while.

And after taking a look at the code, nothing of the statement above changed.

2

u/Technical_Ideal_5439 2d ago edited 1d ago

If you know another language before trying to learn c++ I would say this is a about 20 minutes of learning. Mainly because you used a struct. Basically you are at 0.1 out of 100.

And hopefully you used indentation and it got stuffed up when you pasted it in.

1

u/Born_Juggernaut_346 1d ago

i used indentation, it just sort of stuffed like this

0

u/Technical_Ideal_5439 1d ago edited 1d ago

set you indentation to use 2 or 4 spaces, not tabs and you wont have that problem, it is also the standard for c++.

1

u/Born_Juggernaut_346 1d ago

I usually use tabs cause it feels like it is organized, but since the standard is that I will use it

1

u/Technical_Ideal_5439 1d ago

https://google.github.io/styleguide/cppguide.html

Note they use 2 spaces. But at your stage style guides are are little pointless.

5

u/podule-games 2d ago

Pretty good beginner code, especially for just two weeks since you started learning.

The next step is to write another more advanced program, and you keep going from there.

5

u/D_Drmmr 1d ago

Looks good for a beginner. Since you know how functions work, you can abstract some repeated patterns into reusable functions. E.g. getting input from a user is always the same pattern. Can you make a function for it to reduce code duplication and make it easier to understand what the code does when you read it?

1

u/minimalcation 1d ago

There are no levels

1

u/Born_Juggernaut_346 1d ago

And I don't know what are levels!?

1

u/minimalcation 1d ago

Congrats, you already know

1

u/James-w07 2d ago

building something you can actually use teaches you more than just following tutorials.

2

u/Born_Juggernaut_346 1d ago

I didn't follow any tutorial, I swear I made it all from my mind, every single semicolon was made be me and me alone, I debugged it myself and tested i myself. There was absolutely no tutorial. I wouldn't hide the fact that I had a problem with the vectors which then I revised the whole topic and fixed the problem. Other than that it was all by me. I don't want to sound offended it just felt good that it was a success someone called it a tutorial

2

u/Swackles 1d ago

If you're wandering what to do next. Instead of writing everything to a single file, have every user assaigned their own that gets encrypted using the password

3

u/mredding 1d ago
std::cin >> savedUser;

Always check your input stream:

if(std::cin >> savedUser) {
  // Input is valid
} else {
  // Input error
}

Streams store their iostate, defined as type std::ios_base::iostate. The flags are goodbit, badbit, failbit, and eofbit.

Good is no flags, and EOF is itself not an error, just a state; there's a file descriptor under the hood, and files end, sockets disconnect or close, EOF is allowed to happen.

If the stream is bad, then it has suffered an unrecoverable error. There's nothing more you can do for the stream buffer object that's guaranteed.

A failed stream is recoverable. Usually this is a parsing error. You wanted an int but you got text... You can clear the failbit and reparse or purge, or whatever.

Bad, failed, and EOF can each or all be set at once, in combination. This state variable is the state of the previous IO operation, so when you START your program, std::cin and std::cout will both be good, and won't know if there's a problem until you try something.

Mostly, for simple programs, you write an error message and quit if you encounter a problem.

As your program stands, if there were in input error with savedUser, your program would zip uselessly through two other prompts, no-op both of them, and error. That's not good UI/UX.


system("cls");

You're trying your best to make an interactive and clean terminal program, but not this way. There's no guarantee if you have a command processor available to you, or what it is, or what commands or permissions you have. This isn't portable, and it makes your program vulnerable to command injection attacks. system was perhaps not a good idea, but it's from a bygone era of computing when security concerns weren't what they are today.

If you wanted to make an interactive terminal program, you'd want to pick up a curses library, and perhaps some C++ wrappers around that. curses is one of the oldest, most stable, most mature, most portable system libraries in the C ecosystem. It's a layer of abstraction that turns the standard IO file descriptors into text terminal resources, and then you render the terminal through the library, and basically leave standard streams behind (you don't exactly have to, but that's another discussion).


Ranking getrank(int points)
{
if (points < 250) return Ranking::Trash;
if (points < 500) return Ranking::Intermediate;
if (points < 750) return Ranking::Advanced;
if (points < 1000) return Ranking::Legendary;
return Ranking::Mr_VIP;
}

Clean.


void addUser(std::string username, std::string password, int points)
{
std::ofstream file("users.txt", std::ios::app);
file << username << " ";
file << password  << " ";
file << points << " " << "\n";
}

There are much better ways to do this, but you're nowhere near that lesson yet. In the meantime, how about a little better?

void addUser(std::ostream &os, std::string username, std::string password, int points)
{
os << username << " ";
os << password  << " ";
os << points << " " << "\n";
}

Make the resource the caller's problem.

addUser(std::ofstream{"users.txt", std::ios::app}, name, pw, pts);

Maybe I want to reuse this function to make a more complex data structure, not just a mere row in a flat file, maybe I want active vs inactive users, or some other scheme. Maybe my stream is a socket. Maybe it's standard output. It makes the function more pliable.

After all, it's called addUser, not openFileAndAddUser. Try to reduce functions to one responsibility - it can be a big responsibility, if you can name it well...


for (int attempt = 0; attempt < 3; attempt++)
{
std::string iusername;
std::string ipassword;
std::cout << "Enter your username: ";
std::cin >> iusername;
std::cout << "\n";
std::cout << "Enter your password: ";
std::cin >> ipassword;
std::cout << "\n";

bool found = false;
int foundPoints = 0;

for (const user& u : users)
{
if (u.username == iusername && u.password == ipassword)
{
found = true;
foundPoints = u.points;
break;
}
}

There's a philosophy in programming that for every nested scope, call a function. I said getrank is clean because if we considered if (points < 250) return getTrashValue();, this doesn't ADD anything but confusing complexity. A pragmatic approach suggests intuitive limits.

But this loop? I don't know what it does. I don't want to read it - parse it like I'M the god damn compiler, to try to figure out whatever the fuck it does.

Call a function.

for (int attempt = 0; attempt < 3; attempt++)
{
    find_a_user();
}

Or something. Yes, more needs to be put in here to make it actually work, to stop on success, etc. But the point is the loop body is way too complex. Make the code more readable.

And there are further steps you can take, but it'll require future lessons - I'd make an attempt_n function that takes a limit and a function name, and tries up to n times for the function to succeed.

You'll get there, but you can still improve this as a step toward that. There's a TON of subtlety in any programming language where we separate concerns and create tiny units that each express a single concept and one responsibility. We leverage the language and the compiler to composite work in more expressive ways.

1

u/grady_vuckovic 1d ago

It's a great start, keep at it. Ignore the unhelpful comments here, look for the genuine feedback, plenty has already been given, and before you move on, try rewriting this based on some of the feedback. One of the things you'll do as a programmer far more often than writing code from scratch, is rewriting or changing code based on new requirements, so it's good practice.

1

u/BotSlamminDayNNight 1d ago

just by writing it with no ai is a huge deal. i hire learners. i would probably hire you, confident that wherever you were, whatever your level, you'd be creating value.

1

u/kbr89 1d ago

Two tests you can run on your own program to see what to learn next:

  1. Type a username with a space in it, like `john smith`. `std::cin >>` stops at the first space, so "john" becomes the username, "smith" gets read as the password, and the password prompt doesn't wait for you. `std::getline` reads the whole line and is the fix. It's worth learning now, because mixing `>>` and `getline` has its own trap (the newline left in the buffer).
  2. Run the program twice with the same username and password, first with 100 points and then with 900. Logging in still says "You are trash", because the file now has both lines and your loop stops at the first match. Making the save step check whether the username already exists, and refuse or update it, is a good next exercise: it means reading the file before you write to it.

Smaller one: in main you build `user u` and then pass the three values to addUser separately. `void addUser(const user& u)` uses the struct you already made and avoids copying the strings.

-1

u/notarshzzz 1d ago

For two weeks in, this is genuinely solid — and the part that tells me that isn't the rank names, it's that the program remembers things between runs. A lot of beginners stay in "type input, print output, forget everything" for a long time, and you've already combined a struct, a vector, an enum class, and file reading/writing into one working thing. That combination is the real milestone here.

Two concrete next steps, in order: first, try adding one feature that forces you to change saved data — like letting a user update their points, or deleting a user. That makes you load the file, find the right entry in the vector, change it, and rewrite the file, which is a different skill from just appending. Second, give the password a second thought even in a toy program: right now it's stored in plain text in users.txt, so anyone who opens that file sees it. You don't need a real hashing library yet, but knowing plain-text storage is a habit not to carry into real projects matters.

Don't measure yourself against the "20 minutes" comments — speed at typing code you already understand isn't the same as learning the concepts the first time. You're doing the right thing by building instead of just watching tutorials.

1

u/Born_Juggernaut_346 1d ago edited 1d ago

Thanks, I researched a bit and I saw something called Argon2id, I will try using it. And another user say it has a low level abstraction, so I will just make all the tasks in different functions and just use the main to call them in. Thanks for your opinion, it was really helpful

3

u/greenpepperpasta 1d ago

FYI, the comment you replied to was definitely written by an AI.

2

u/Born_Juggernaut_346 1d ago

You think so. It does seem too organized to be human written, but it felt wrong to judge someone appraisal

2

u/greenpepperpasta 1d ago

I use Claude on a regular basis at work and the tone/style of the comment sound just like it. Perhaps this person was using it just to organize their own ideas into a polished comment, or perhaps they didn't even read your code and posted a low effort AI review for free karma. I'll refrain from judging which I think is more likely.

1

u/notarshzzz 1d ago

bro ran a full investigation under a comment that already helped him. op read it, he's literally adding argon2id right now. all that detective work and you still helped nobody in this thread

0

u/minimalcation 1d ago

So? Is the advice or review bad?

1

u/notarshzzz 1d ago

argon2id's a solid pick, good luck with it — and yeah splitting stuff into functions will make the next version way easier to read