r/learnprogramming • u/Born_Juggernaut_346 • 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
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!
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.
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/James-w07 2d ago
building something you can actually use teaches you more than just following tutorials.
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
Always check your input stream:
Streams store their
iostate, defined as typestd::ios_base::iostate. The flags aregoodbit,badbit,failbit, andeofbit.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
intbut you got text... You can clear thefailbitand 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::cinandstd::coutwill 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.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.
systemwas 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
curseslibrary, and perhaps some C++ wrappers around that.cursesis 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).Clean.
There are much better ways to do this, but you're nowhere near that lesson yet. In the meantime, how about a little better?
Make the resource the caller's problem.
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, notopenFileAndAddUser. Try to reduce functions to one responsibility - it can be a big responsibility, if you can name it well...There's a philosophy in programming that for every nested scope, call a function. I said
getrankis clean because if we consideredif (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.
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_nfunction that takes a limit and a function name, and tries up tontimes 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:
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.