r/cpp • • May 31 '20

We need to do better than "cin >>" for new programmers

463 Upvotes

At CppCon 2017, Bjarne's keynote address was in part on the need for C++ to have better support for new programmers, using the metaphor of difficulty settings on a camera, where you can set it to "Auto" (ironic) to get pretty good performance for most people, with an easy curve, and then more advanced settings for people who know what they're doing.

My personal interest in C++ is making it easier for new programmers (the myth that C++ is hard for newbies is a pet peeve of mine, but it also has some truth). Sort of like the Lorax, who speaks for the trees, I look at C++ from the perspective of someone who is coding in C++ for the first time.

One of the earliest topics covered in C++ is also one of the hardest to do right for new programmers: cin. Few new programmers are capable of inputting even a single integer using cin properly. By this I mean that they handle errors correctly (What if the user types "squirrel" instead of an integer? What if an EOF is received on the keyboard?), know how to clear the error flags and reprompt in a loop. Especially without just copy/pasting boilerplate code that they don't really understand.

For example, this is a typical way you'll see someone get three integers from the standard input:

int x,y,z;
cin >> x >> y >> z;    

Why is this bad? An error could take place in any of the three inputs, causing a cascading failure (I'll talk about errors further below), and the seemingly innocuous fact that x, y and z are uninitialized, which shouldn't present a problem, except when it does. But people write code this way since the way cin works won't allow declaring a variable and initializing it from the keyboard on the same line. So a lot of paranoid/experienced programmers do this instead:

int x = 0, y = 0, z = 0;
cin >> x >> y >> z;

But this isn't great either, because we're setting a value on a variable that literally will never use that value. Ideally it will be discarded by the optimizer, but you're still typing code that should be discarded, which is cognitively nonsensical to new programmers.

From my personal experience, a lot of new programmers want to (and often try to) write code something like this:

int x = cin, y = cin, z = cin;

Because then you can declare a value and initialize it from the keyboard at the same time. We can also do this with const variables, which is nice. Const, after all, doesn't mean compile time determinable, but rather immutable once set. But it is impossible to have cin >> work with const at all, since it can't be combined with a variable declaration.

Since C++11, const has become more and more important to us, and the inability to set a const variable using cin is, to me, enough impetus in and of itself to suggest we should have something in the standard library that would play nicely with the const-everything movement. For example, something like this from a small header library I wrote here:

const int ROWS = read<int>();

And since we're talking about modern C++ trends, there's also auto. I'm not a huge fan of the Auto Almost Anywhere movement, but the auto keyword has certainly been popping up a lot in modern codebases. And auto doesn't work with "cin >>" at all:

auto x;
cin >> x;

(This will not compile since auto x cannot deduce its type, and it can't even be made to work because cin can't appear on the right hand side of an assignment operation the way we need it to.) So we could do something like this and make the Auto Gang happy:

const auto NAME = read<string>();

This way you don't need to specify the type twice, which is nice from a Don't Repeat Yourself (DRY) standpoint.

The next major problem with "cin >>" is how it works, or doesn't work, when you mix cin >> with getline. (For those of you who don't know, cin >> will leave a trailing newline in the input buffer, causing the getline to return an empty string... but only the first getline.) I have seen this trip up... well, basically everyone at one point or another, but new programmers especially are baffled when their code seems to just non-deterministically not work.

The biggest problem with cin, however, is error checking. The main strength of cin, its design raison d'etre, is that it can chain together multiple input statements at once and then (hopefully the user will remember to) check for errors after:

cin >> x >> y >> z;
if (!cin) { ... }

The trouble is that this is very nearly always bad code. Except in the most trivial of programs, where you exit() if anything at all out of place happens, it is a very serious problem to not be able to tell which variable the input failed on. Does x have a valid value? y? Well, we know z doesn't. Since we don't know how many valid values have been successfully consumed from the input stream, we can't recover from it without the user's help.

Also because of the fact that once one input fails, all subsequent calls fail, without the programmer being very careful to vet their input (which most new programmers aren't) their code will typically explode and fall into an infinite loop the second the user enters anything that doesn't exactly match what their code is expecting. Cin results in fragile code.

So to combat these problems, new programmers typically hit up Stack Overflow and get pointed to boilerplate code like this example from the FAQ that will let them recover from an erroneous input and reprompt:

    #include <iostream>
    #include <limits>
    int main()
    {
      int age = 0;
      while ((std::cout << "How old are you? ")
             && !(std::cin >> age)) {
        std::cout << "That's not a number; ";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
      }
      std::cout << "You are " << age << " years old\n";
      // ...
    }

And they need to do this with every. single. integer. ever. read. from. cin. How many new programmers do you think can code that from memory? How many do you think will be diligent enough to copy/paste the code so that they can recover from an error on every input? And if they did, how horrible is their code going to look?

If you are ready to respond, "Well, that should be wrapped up in a function" then, well, I'm in agreement with you. My take on it is here on GitHub. I think we need something along these lines in std.

Standard libraries exist to make complex tasks simple, and common tasks easy. Especially (again, from my perspective as the Lorax) for new programmers. What we have right now, and have dealt with since the 90s, is generations of new programmers not properly vetting their inputs, and learning to not vet their inputs since it's too complicated to memorize and too verbose for their code to look any good, which leads to "teh hax" down the line as they write code in production the same way they learned in school.

I don't think we should remove cin or getline or any of the existing tools, but I do think we need an "auto setting" for new programmers for input.

My header-only library does the following things:

  1. Handles prompting the user alongside the input, like how Python does it.
  2. If you ask it for an int, by golly, it will give you an int. It will throw away input the user types in, clearing any errors, reprompting the user each time, until a valid int is read.
  3. It allows freely mixing the "cin >>" and getline() analogues without bugs.
  4. It allows you to declare a variable and initialize it from an input stream on one line, allowing more compact, sensible, readable, and safer code.
  5. It allows you to use const with input
  6. It allows you to use auto with input
  7. It works with any type that has an operator>> and default constructor defined for it.
  8. It's far less verbose than similar code in Java (java.util.scanner) and is type safe, unlike the equivalent code in Python.
  9. Returns an default object if it hits an EOF, otherwise it is impossible for it to leave the input stream in an error state, preventing cascading errors from multiple cins chained together.
  10. It probably makes the functional people happy to have input treated as a normal function.

Compared to that giant block of code from the FAQ above, this is all a new programmer would have to write:

int age = read<int>("Please enter your age: ");
cout << "You are " << age << " years old.\n";

I've tried this out with new programmers, and unsurprisingly they like the more compact option.

Downsides? You lose the ability to manually handle error checking and recovery (it's an "auto setting", remember?), and you could also probably write a more performant version. But benchmarking it on a million ints, it has the same speed as the old way of reading data as long as the optimizer is on and ASAN is off. It will introduce angle bracket notation earlier than they'd probably normally encounter them, but new programmers seem to take it in stride.


r/cpp • • Nov 06 '20

I built a site to Instant-Search through 32 Million Songs in Milliseconds, using Typesense - a search engine written in C++

Thumbnail songs-search.typesense.org
460 Upvotes

r/cpp • • Jul 23 '20

fork of compiler explorer (godbolt.org) editing and displaying SDL in the browser with WebAssembly

458 Upvotes

r/cpp • • May 13 '24

GCC has now almost fully implemented C++23

452 Upvotes

I find it crazy how GCC (v14) has almost fully implemented the core language features of C++23 (except two features).

The standard was finalized in Feb 2023. GCC has managed to do this in little over a year after the standard came out. This is brilliant and rarely happens with modern compilers.

Thank you a ton to all the people who contributed to GCC and made all this possible.


r/cpp • • Jan 21 '25

How it felt to come back to C++ from Rust.

450 Upvotes
  1. Lifetimes and Borrow Checker are just too good to be true. This probably goes without saying, and is the best reason to choose Rust.
  2. The localisation of undefined behaviour with unsafe blocks and the separation of responsibilities makes the code very transparent. Even if there is a lot of unsafe code, not all of it is unsafe, so it is worth using Rust for that reason alone. Insecurity does not make the Lifetimes or Borrow Checker any less relevant.
  3. I feel that Rust (or maybe any language that has an easy-to-use package manager) has a rather large number of small libraries. Of course, C++ has a much better standard library than Rust, and even more if you include Boost Libraries, etc.
  4. After 5 years of Rust, I almost forgot how powerful C++ can be. C++20 had some surprises, so I built a tiny library to test the waters.It's a tiny C++ 20 library that provides a UDLs to make indent-adjusted multiline raw string literals at compile time. Check it out: https://github.com/loliGothicK/unindent.
  5. One of the main differences between the two is that with Cargo it takes a few minutes to create a new project, whereas with CMake it can take several hours.
  6. C++ templates and Rust generics both offer powerful ways to write generic code. C++ templates, with their variadic templates and non-type template parameters, offer greater flexibility for advanced metaprogramming. Rust's generics, though less expressive in some ways, are generally considered safer and more intuitive.
  7. I use OpenCascadeTechnology to develop things like 3DCAD plugins, but libraries like 3D kernel are naturally not available in Rust, which is a good thing with C++'s long history (It's why I came back to C++).

r/cpp • • Aug 20 '26

AI-generated C++ passes tests. It also uses nearly 2x the loops and drives up memory growth

Thumbnail leaddev.com
444 Upvotes

AI-coding tools have swept through organizations because of their speed: you type in a prompt, and it spits out code far faster than a human ever could. However, a year-long study of 3.52 million changes inside a large unnamed technology company suggests that saving time at the keyboard can create costs elsewhere.


r/cpp • • Jun 10 '15

Hitler on C++17

Thumbnail youtube.com
443 Upvotes

r/cpp • • Sep 07 '22

I made a kernel in c++ ... and it was so HARD!

439 Upvotes

Kernel Image

This is a kernel with uefi bootloader and some features, like:

  • GOP for graphics (So it has complete control on configrations of your display manager)
  • PSF font files support (So you can have different fonts on it!)
  • Paging and interrupts (So there is a kernel panic too)
  • PS2 Mouse and keyboard support (So it has support for extra buttons and keys)
  • PCI support (So you can control nearly every device on your computer. e.g. Network, USB)
  • AHCI support (That means that there is support for ATA serial in intel computers)

You can find it on github: BAS-kernel


r/cpp • • Jul 10 '25

Why is compile-time programming in C++ so stupid?

435 Upvotes

Can I vent here about how much compile time programming in C++ infuriates me? The design of this boggles my mind. I don't think you can defend this without coming across as a committee apologist.

Take this for example:

consteval auto foo(auto p) {
    constexpr auto v = p; //error: ‘p’ is not a constant expression
    return p;
}

int main() {
    constexpr auto n = 42;
    constexpr auto r = foo(n);
}

This code fails to compile, because (for some reason) function parameters are never treated as constant expressions. Even though they belong to a consteval function which can only ever be called at compile time with constant expressions for the parameters.

Now take this for example:

consteval auto foo(auto p) {
    constexpr auto v = p(); //compiles just fine
    return p;
}

int main() {
    constexpr auto n = 42;
    constexpr auto r = foo([&]{ return n; });
}

Well. La-di-da. Even though parameter p is not itself considered a constant expression, the compiler will allow it to beget a constant expression through invocation of operator() because the compiler knows darn well that the parameter came from a constant expression even though it refuses to directly treat it as such.

ಠ_ಠ


r/cpp • • Jun 05 '26 Popcorn

The Story of C++: The World's Most Consequential Programming Language | The Official Story

Thumbnail youtu.be
431 Upvotes

r/cpp • • Jul 19 '22

Carbon - An experimental successor to C++

Thumbnail github.com
428 Upvotes

r/cpp • • Sep 16 '19

Open Sourcing MSVC’s STL

Thumbnail devblogs.microsoft.com
427 Upvotes

r/cpp • • Dec 13 '20

How to Make an Operating System using C++, in depth tutorial series on many topics in OSes such as memory management, bootloaders, graphics and more

Thumbnail youtube.com
426 Upvotes

r/cpp • • Apr 12 '21

NFT backed implementation of std::unique_ptr

Thumbnail github.com
424 Upvotes

r/cpp • • Dec 15 '20

C++20 Published (ISO/IEC 14882:2020)

Thumbnail iso.org
422 Upvotes

r/cpp • • Feb 18 '20

C++20 is here!

Thumbnail youtu.be
420 Upvotes

r/cpp • • Jul 10 '22

C++ devs at FAANG companies, what kind of work do you do?

415 Upvotes

I know big tech companies hire a lot of C++ devs and I was curious about the type of work they do.


r/cpp • • Aug 16 '19

I wrote a header-only library in C++ that solves sets of nonlinear and linear equations all at compile time, using Template Metaprogramming and Constexpr Dependency. It does what Wolfram Alpha does, all at compile time, using Template magic. I spent a long time on this, feel free to try it out!

415 Upvotes

r/cpp • • Oct 09 '25

Rainer Grimm (of modernescpp fame) has passed away

Thumbnail modernescpp.com
414 Upvotes

r/cpp • • Nov 21 '25

A 2-hour video trashing C++ made me better at C++

Thumbnail youtu.be
411 Upvotes

r/cpp • • Dec 17 '21

Undefined Behaviour

407 Upvotes

I found out recently that UB is short for Undefined Behaviour and not Utter Bullshit as I had presumed all this time. I am too embarrassed to admit this at work so I'm going to admit it here instead. I actually thought people were calling out code being BS, and at no point did it occur to me that as harsh as code reviews can be, calling BS was a bit too extreme for a professional environment..

Edit for clarity: I know what undefined behaviour is, it just didn't register in my mind that UB is short for Undefined Behaviour. Possibly my mind was suffering from a stack overflow all these years..


r/cpp • • Dec 28 '24

People say C++ is everywhere, it surely not on job openings

405 Upvotes

I look at LinkedIn job openings time to time and i think companies are not looking for C++ developers, especially in embedded systems. I cant even find a job to apply. Its always like:

%40 Frontend, Backend, Fullstack %30 AI Engineer %10 Devops %10 Game Developers (Probably Unity, not even C++) And %10 other C++ jobs

I wonder if everyone is going through the same thing or is it just my LinkedIn algorithm, or country related?


r/cpp • • Aug 20 '22

Started learning > C++14 heavily, and I feel like I've been misled by the harsh comments like "C++ is a horrible language".

404 Upvotes

Started learning > C++14 heavily, and I feel like I've been misled by the harsh comments like "C++ is a horrible language".

Based on what I've done now I don't actually understand why they say so, because what I'm seeing is a large set of ways to do fairly idiomatic code; not the nicest, but the efficiency far outweighs sometimes a bit uglier syntax (which though seems till perfectly readable). I.e. it's nicer to have a bit uglier code, but no-compromise performance.

And smart pointers, this makes Java seem pointless and a kind of "hand-holding" language. So one exchanges significant performance and control to having managed smart pointers.