In my simple program to learn C++, I am asking the user their name and then greeting them.
#include <iostream>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!\n";
}
However, here is my result in CLion:
I expected the program to print out a trailing whitespace after the prompt for my name. However, it prints the space after I give the program input. I have only experienced this in CLion, but not in other IDEs. Why is this happening, and how can I fix this?
You need to flush your stream:
std::cout << "Enter your name: " << std::flush;
std::cout is a buffered stream which means that while your write to it isn't immediately written to the underlying device, but it is stored in a buffer. This is done for performance reasons. std::endl has an implicit flush operation, that's why you don't notice this if you always add a std::endl before you request input. Otherwise, like you've seen that can happen.
Related
Here is an example code demonstrating the problem I'm facing.
#include <iostream>
#include <string>
extern "C" {
#include <unistd.h>
}
int main()
{
std::cout << "Making tests ready!" << std::endl;
std::cout << "\nTo start out, Enter an integer: ";
int a = 0;
std::cin >> a;
std::string input;
sleep(3); // what to do if user enters data during this?
std::cout << "\n Now enter a string";
std::getline(std::cin, input);
std::cout << "\nHere are your values - " << a << " & " << input;
return 0;
}
See the sleep call in between the code? This could be replaced with somewhat long delays while computing something when my program isn't accepting any inputs. Now if user presses some keys during this time, that input is captured by std::getline() in next line of code. I know this is the default behavior since it should capture the input being provided.
But what I want is to clear all that captured input and start fresh with 15th line that is std::cout << "\n Now enter a string";, which is immediately after sleep. I don't know exact term to describe this or else I would have used that. Thanking you.
Edit: I've tried using std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); in my code, but it asks for input and then discards it.
Please mind my english, not a native speaker.
Reading the comments causes me to think that you can't really solve this problem (at least by the means suggested there). There's an inherent race condition in any case. Consider the following lines:
sleep(3);
// (*) <- Potential location 1.
std::cout << "\n Now enter a string";
// (**) <- Potential location 2.
std::getline(std::cin, input);
The various comments show some (very technically-competent) ways to flush the standard input. The problem is, you cannot put them in the location marked (*) nor (**).
First location - you clear the standard input some way. Now you decide it's time to move to the next line (std::cout << ...). While you do that, the user types in some more input. Race!
Second location - You print out the message (std::cout << ...), and proceed to clear the standard input. Before you manage to do that, the user typed in something. Race!
It seems to me that any of the techniques described in the comment require locking the standard input, and I don't think there's a (standard) way to do so.
I am beginner at C++, my question is can I remove endl the one at the end of cout like :
cout<<" "<<endl;
I don't want return to new line . If I can't remove it, what should I do?
Elephant in the room: remove the endl from the cout.
But in case you don't own that code, you could try "\033[F", which, if your terminal supports it, moves you to the previous line.
Another possibility would be to redirect the cout buffer using rdbuf to an ostream that you control. You could (i) redirect, (ii) call the function that writes the errant cout with the new line and (iii) inspect your ostream and write to the original buffer, this time omitting the endl. Switch everything back once you're done.
Yes of course you do not need to use std::endl every time you use <<. As an example a simple way to print a vector with spaces between the elements would look like:
std::vector<int> foo = {1,2,3,4,5};
for (auto e : foo)
std::cout << e << " ";
Here we never use a endl. You cout also just use \n at the end of a string literal and that will put a newline in the buffer as well.
std::cout << "test\n";
std::cout << "this will be on a new line";
Notice that I don't put a newline in the last cout<< so if there is anymore output it will start off right after the "e" in "line".
Yes you can remove endl. It is an optional parameter to the << stream operator of which there are many. If you don't include it then a new Carriage Return/Line Feed character will not be output and therefore text will appear on the same line in the output (presumably console).
For example
cout << "Hello, World" << endl;
would become:
cout << "Hello, World";
or to make the point another way you could write:
cout << "Hello,";
cout << " World";
There are lots of other examples out there too, here's one for starters: http://www.cplusplus.com/doc/tutorial/basic_io/
cout<<"Your message here.";
It's as simple as that. Were you trying to do something like...
cout<<"Your message here."<<; ....? This is wrong as:
The << operator signifies that something comes after the "" part. You don't have any in this case.
So if I write a piece of code like this:
string name, feeling;
cout << What is your name?" << endl;
cin >> name;
cout << "Hello, " << name << "!"<<endl;
cout << "So how are you feeling today?" << endl;
cin >> feeling;
I get the output:
What is your name?
James (input from user)
Hello, James!
So how are you feeling today?`
But I want it to remove the first message and the input, so the user will get just this on the console window:
Hello, James!
So how are you feeling today?
As long as you stay on the same line, it's usually pretty easy to use a combination of \b (back-space) and/or \r (carriage return without new-line) and some spaces to go back to the beginning of a line and write over what's displayed there.
If you need to do (much) more than that, you can use the Windows console functions such as SetConsoleCursorPosition and FillConsoleOutputCharacter to write data where you want it, overwrite existing data, etc.
If you care about portability to Linux and such, or already know how to program with curses, you might prefer to use PDCurses instead. This is basically a re-implementation of the ncurses programming interface on top of the Windows console functions.
If you work on windows environment, try this
#include <iostream>
int main()
{
std::cout << "This is the first line";
system("cls");
std::cout << "This is the line on clear console" << std::endl;
return 0;
}
I am writing a fairly simple exercise (homework), and most of it works, however it sometimes segfaults on cin. Here is the relevant code.
int main()
{
std::string str = "";
std::cout << "Please select the desired operation:\n";
std::cout << "(A): Generate Decompositions\n";
std::cout << "(B): Generate Acceptable Compositions from S1.txt and S2.txt\n";
std::cout << "cout"; //debug statement
std::cin >> str;
std::cout << "cin"; //debug statement
std::cout << str;
char resp = str.at(0);
std::cout << "resp"; //debug statement
...
}
I get a segfault on std::cin >> str (I know this because of what "debug statements" are output). But the weird thing is, I only get it when I input 'b'. If I input 'a', or any word starting with 'a', it works fine. If I enter any letter other than a or b, or anything starting with any other letter than a or b, it exits (as it's supposed to). But if I type in 'b', or any word starting with 'b', it Segfaults. Every single time. Why?
I know this because of what "debug statements" are output"
The code that you posted looks fine.
Since your output statements do not have << endl at the end, some of the output may still be buffered at the time of segfault. Writing out endl blocks until the output is flushed, so adding << endl is likely to help you get closer to the actual location of the crash.
I know this is a noob question. I used this example code from here. How is it supposed to work? I thought you can input something for who but it just closes immediately.
#include <iostream>
#include "getopt_pp_standalone.h"
using namespace GetOpt;
using namespace std;
int main(int argc, char* argv[])
{
string who;
GetOpt_pp ops(argc, argv);
ops >> Option('n', "name", who, "world" ); /* the default name is 'world' */
cout << "Hello " << who << "!" << endl;
return 0;
}
Variants of getopt get options from the command line rather than input by a user.
You will need to run your program with something like:
myprog -n Pax
If you want interactive input from the user, get rid of the getopt stuff altogether and just use the streams, such as:
std::cout << "Identify yourself, interloper!\n";
std::cin >> who;
std::cout << "Hello, " << who << ", my name is Pax.\n";
A few other things to impart:
First, you may need to put a getchar() (or cin >> who) before the return if you're running in an IDE that closes the execution window instead of waiting. Otherwise, the output will go to the window and immediately disappear.
Second, while it's probably okay for small programs, using namespace std can cause problems with more substantial projects (in terms of polluting the standard namespace, see here for a good explanation). I prefer to fully qualify my calls, such as:
std::cout << "blah, blah, blah\n";
Third, endl is used far too often by most developers. Most times you should just either use '\n' instead, or just tack on \n to the end of a string like "Hello, world!\n". That's because the \n way doesn't force possibly inefficient flushing of the stream like endl does. That's covered here.