Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 4660

SDK • Almost certainly me but what is wrong? Or is it a bug?

$
0
0
I thought I'd have a play with C++ on the Pico so loaded the following simple program. I'm a complete beginner at C++

Code:

#include <stdio.h>#include "pico/stdlib.h"#include <iostream>int main(){    stdio_init_all();    busy_wait_ms(1000);    while(1)    {        std::cout << "Enter a number: "; // ask user for a number        int x{}; // define variable x to hold user input        std::cin >> x; // get number from keyboard and store it in variable x        std::cin.clear(); //get rid of anything else in the input         std::cout << "You entered " << x << '\n';    } }
This works perfectly as expected if I enter a number. If I enter a letter the program immediately prints 0 which is correct but then, irrespective of what way I try and clear the input stream, it loops continuously printing 0.
I've google clearing cin and tried a range of variants: cin.sync(), cin.ignore(), std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n')

It only does what I want if I add
fflush(stdin);
after the cin.clear

But, as I understand it, this shouldn't be necessary and google suggests will make the code non-portable by using a function with an undefined result

Statistics: Posted by matherp — Sat Jan 04, 2025 1:37 pm — Replies 3 — Views 74



Viewing all articles
Browse latest Browse all 4660

Trending Articles