Stop new line for C++ cin - c++

In C++, iostream automatically puts in a new line after cin. Is there a way to get rid of this?
I want use iomanip to format information into a table, like so:
cin cout
0.078125 3DA00000
-8.75 C10C0000
23.5 41BC0000
(random numbers)
example code:
#include <iostream>
using namespace std;
int main()
{
int num;
cin >> num; //now a new line.
cout << num << endl;
return 0;
}

You presumably pressed the return key to send your input from the command line to your program's standard input. That's where the newline is coming from. You can't read your number from cin before this newline appears in the console, because the newline is what causes the console to hand your input over to the program in the first place. You could, as a user, configure your console (or whatever is running your program) to act differently, but there's no way for the program itself to force such behavior.
If you really want to have your input and your output on the same line, you need to find a way to "write to the previous line". How that works depends on your console (see also How to rollback lines from cout?). There is no standard way to do this because cin and cout are in no way obligated to be attached to a console or anything resembling one, so it is not clear that "writing to the previous line" even means anything.

'endl' makes a new line just don't use it.
cout << num;

Related

Proper use of EOF (can it be used multiple times in a program?)

In my intro to programming course (c++), the instructor told us to:
"Write a program that inputs an unspecified number of integer ("int")
values and then outputs the minimum value and the maximum value that
were entered. At least one value will always be input. (read all input
until EOF). For extra credit make your program also work when the user
doesn't enter any ints at all (just the EOF.)"
I wanted to get fancy, so, in my solution, when just EOF is entered, the program responds with "Oops! You didn't enter anything. Please try again, this time entering at least one integer: " and prompts for input again.
My instructor is saying that this answer is wrong because
After the EOF, there should be no more input to a program (neither
expected by the user nor the program) — using the EOF to switch from
“one mode” of input to another mode of input isn’t supporting the
standards.
Every definition of EOF I've found on the internet doesn't seem to support my professor's definition. EOF, from what I can tell, is simply defined as the end of the current file. It seems perfectly valid to accept input from a user until EOF, do something with that input, and then ask for additional input until EOF again.
Because this is an online course, I was able to review everything we learned relating to EOF and we were only told that EOF meant "End of File" and could be 'used to signal an end to user input' (important, because, even if my professor was wrong, one could argue that I should have adopted his standards if he had specifically told us to. But he didn't tell us to).
What is the proper way to use EOF with user input? Is my professor's statement that "After the EOF, there should be no more input to a program" the standard
and expected way to use EOF? If a program accepts a variable amount of input, does something with it, and then accepts more variable input, is it not acceptable to use EOF with those inputs (aka don't use while(cin >> user_input) in that scenerio)? If so, is there a standard for what should be used to signal end of input in a scenario where you're accepting variable input multiple times?
My exact solution to the assignment is below. My solution to the main assignment "Write a program that inputs an unspecified number of integer ("int") values and then outputs the minimum value and the maximum value that were entered" was considered correct, by the second part of the assignment "make your program also work when the user doesn't enter any ints at all (just the EOF.)" was deemed incorrect ("make the program also work" is the only prompt we were given).
Thanks so much for any feedback!! Obviously, I'm skeptical of my professors feedback / decision, but, in general, I'm just trying to get a sense of C++ community standards.
#include <iostream>
#include <iomanip>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
string user_input;
int int_input, min_user_input, max_user_input;
bool do_it = true;
cout << "Hi John," << endl;
cout << "Please enter a few integers (signal EOF when finished): ";
while(do_it) {
cin.clear();
cin >> user_input;
if (user_input.empty()) {
cout << endl;
cout << "Oops! You didn't enter anything. Please try again, this time entering at least one integer: ";
}
else {
try {
int_input = atoi( user_input.c_str() );
min_user_input = int_input;
max_user_input = int_input;
while(cin >> int_input) {
if (min_user_input > int_input) {
min_user_input = int_input;
}
if (max_user_input < int_input) {
max_user_input = int_input;
}
}
cout << endl;
cout << "The max user input was: " << max_user_input << endl;
cout << "The min user input was: " << min_user_input << endl;
do_it = false;
}
catch (std::invalid_argument) {
cout << endl;
cout << "Oops! You didn't enter an integer. Please try again, this time only entering integers: ";
do_it = true;
}
}
}
return 0;
}
Note: additional feedback I got on this submission was: to not use c libraries (apparently stdlib.h is one) and that, on some computers (though, apparently, not mine), #include <stdexcept> will be needed to compile.
Answer
Short answer: my instructor is correct. When used with cin, no additional user input should follow an EOF signal. Apparently, in some cases the program won't let you enter more information, but, as #hvd points out
Although your system may let you continue reading from the same file
in the specific case that it is coming from a TTY, due to EOF being
faked there, you shouldn't generally rely on that.
Aka, because I'm using a terminal to enter user input, the program happens to work. In general, it won't work though.
As #RSahu answers, EOF just shouldn't be used to signal the end of variable length cin multiple times in a program. Importantly
There is no standard means, or commonly practiced coding standard, of
indicating when user input has ended for the time being. You'll have
to come up with your own mechanism. For example, if the user enters
"end", you can use it to deduce that the user has ended input for the
time being. However, you have to indicate to the user that that's what
they need to enter. Of course, you have to write code to deal with
such input.
Because this assignment required the use of EOF, what I was attempting to accomplish was, unintentionally, prohibited (aka receive input, check it, possibly receive more input).
Proper use of EOF (can it be used multiple times in a program?)
There is no single EOF. There is EOF associated with every input stream.
If you are reading from a file, you can reset the state of the std::ifstream when it reaches EOF to allow you to read the contents of the file again.
However, if you are reading data from std::cin, once EOF is reached, you can't read from std::cin any more.
In the context of your program, your professor is right. They are most likely talking about reading from std::cin.
EOF, from what I can tell, is simply defined as the end of the current file.
It is. Note that in particular, what it doesn't mean is the automatic start of a new file.
Although your system may let you continue reading from the same file in the specific case that it is coming from a TTY, due to EOF being faked there, you shouldn't generally rely on that. Try program </dev/null and see happens when you try to automate your program.

C++ getline(cin, variable) is misbehaving. No solutions on the site have helped

My code is rather simple. I have a method called promptUserInput that is defined in UtilityFunctions.h; it is implemented in UtilityFunctions.cpp.
My main method includes UtilityFunctions.h. I've correctly written my makefile, and it compiles without issue.
My main method's first line reads:
string input = promptUserInput();
And here's the actual implementation of the promptUserInput function:
/* Prompts user to enter expression */
string promptUserInput()
{
string userInput;
cout << "> ";
getline(cin, userInput);
return userInput;
}
But when the program runs, it doesn't display the > symbol. Instead, there's an empty line waiting for user input. I enter some arbitrary character, hit Enter, and the > symbol appears afterwards. None of this makes sense to me. What's going on?
std::cout uses buffered output, which should always be flushed. You can achieve this by using std::cout.flush() or std::cout << std::flush.
You can also use std::cout << std::endl, which writes a line break and then flushes, but the line break might not satisfy your intention.

Visual C++ using Console: Char/String compatibility issues with while loop

cout << "Would you like to make another transaction? (y/n)" << endl;
cin >> repeat_transaction;
static_cast<char>(repeat_transaction);
while (repeat_transaction != 'y' && repeat_transaction != 'n')
{
cout << "Invalid selection: Please enter y or n";
cin >> repeat_transaction;
static_cast<char>(repeat_transaction);
}
During the Invalid selection loop, I once accidentally pressed "mn". I noticed the console read out Invalid selection..., So, it did in fact finish and re-enter the while loop. However, after this the console terminated the program. If you enter a single character 'a' or 'y' or 'n' it acts just as it should. Ending or not ending. This was before I attempted to use static_cast to force the truncation of the user input.
Since you managed to get this program to compile I can only assume that repeat_transaction was specified as a char and not a std::string.
When you use cin to get a character it only gets one character but it doesn't flush the buffer. I believe you understand this issue since you wrote This was before I attempted to use static_cast to force the truncation of the user input. . You can attempt to use cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); instead of static_cast<char>(repeat_transaction); after each call to cin >> repeat_transaction; . There are downsides to this. If you enter 'mn' it will work as expected. It reads the m which is not y or n and then flushes the extra characters until it finds end of line \n. If you do nm, n will match and the m will be thrown away. So in that case it will accept nm as valid and exit the loop.
There are other ways that may be easier and give you the effect closer to what you are looking for. Instead of reading a character at a time you can read an entire line into a string using getline (See the C++ documentation for more information). You can then check if the length of the string is not equal to 1 character. If it's not length 1 then it is invalid input. If it is 1 then you want to check for y and n. Although basic (and not overly complex) this code would do a reasonable job:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string repeat_transaction;
cout << "Would you like to make another transaction? (y/n)" << endl;
getline(cin, repeat_transaction);
while (repeat_transaction.length() != 1 || (repeat_transaction != "y" && repeat_transaction != "n"))
{
cout << "Invalid selection: Please enter y or n";
getline(cin, repeat_transaction);
}
return 0;
}
I said reasonable job since one deficiency you might see is that you want to trim white spaces from the beginning and end. If someone enters n or y with a space or tab in front it will be seen as invalid (whitespace at the end would be similar). This may not be an issue for you, but I thought I would mention it.
On a final note, you may have noticed I used using namespace std;. I did so to match what was in the original question. However, this is normally considered bad practice and should be avoided. These StackOverflow answers try to explain the issues. It is better to not do it and prepend all standard library references with std::. For example string would be std::string, cin would be std::cin etc.

How do I input variables using cin without creating a new line?

Whenever I input a variable using cin, after one hits enter it automatically goes to a new line. I'm curious if there's a way to use cin without having it go to a new line. I'm wanting to cin and cout multiple things on the same line in the command prompt. Is this possible?
You can't use cin or any other standard input for this. But it is certainly possible to get the effect you are going for. I see you're on Windows using Visual Studio, so you can use, for example, _getch. Here's an example that reads until the next whitespace and stores the result in a string.
#include <conio.h> // for _getch
std::string get_word()
{
std::string word;
char c = _getch();
while (!std::isspace(c))
{
word.push_back(c);
std::cout << c;
c = _getch();
}
std::cout << c;
return word;
}
It's not very good. For example, it doesn't handle non printing character input very well. But it should give you an idea of what you need to do. You might also be interested in the Windows API keyboard functions.
If you want a wider audience, you will want to look into some cross-platform libraries, like SFML or SDL.
you can also use space for input instead of enter
something like this:
cin >> a >> b >> c;
and in input you type
10 20 30
then
a=10
b=20
c=30
As others have noted, you can't do this with cin, but you could do it with getchar(). What you would have to do is:
collect each character individually using getchar() (adding each to the end of a string as it is read in, for instance), then
after reading each character, decide when you've reached the end of one variable's value (e.g. by detecting one or more ' ' characters in the input, if you're reading in int or double values), then
if you've reached the end of the text for a variable, convert the string of characters that you've built into a variable of the appropriate type (e.g. int, double, etc.), then
output any content onto the line that might be required, and then
continue for the next variable that you're reading in.
Handling errors robustly would be complicated so I haven't written any code for this, but you can see the approach that you could use.
I don't think what you want to do can be achieved with cin. What you can do is to write all your input in one line, with a delimiter of your choosing, and parse the input string.
It is not possible. To quote #Bo Persson, it's not something controlled by C++, but rather the console window.
I can't comment but if you leave spaces between integers then you can get the desired effect. This works with cin too.
int a, b, c;
cin>>a; cin>>b; cin>>c;
If you enter your values as 10 20 30 then they will get stored in a, b, and c respectively.
just use the gotoxy statement. you can press 'enter' and input values in the same line
for eg. in the input of a 3*3 matrix:
#include<iostream.h>
#include<conio.h>
void main()
{clrscr();
int a[20][20],x,y;
cout<<"Enter the matrix:\n ";
for(int r=2;r<7;r+=2)
for(int c=2;c<7;c+=2)
{gotoxy(c,r);
cin>>a[r][c];
}
getch();}

C instruction is being reordered when cin cout and gets is used consecutively

Does anyone knows why C instruction is being reordered when cin cout and gets is used consecutively here?
I am using Dev-C++ 4.9.9.2.
#include<iostream>
using namespace std;
int main(){
char a[10],b;
for(;;){
cout<<"\ncin>>b:";
cin>>b;
cout<<"gets(a):";
gets(a);
cout<<"cout<<a<<b:"<<a<<" "<<b<<"\n\n";
}
}
I got an output like:
cin>>b:132
gets(a):cout<<a<<b:32 1
cin>>b:465
gets(a):cout<<a<<b:65 4
cin>>b:312242
gets(a):cout<<a<<b:12242 3
cin>>b:1
gets(a):cout<<a<<b: 1
cin>>b:
It seemed like some input for cin was passed in gets.. and it also appears that instructions were reordered like:
cin>>b;
gets(a);
cout<<"gets(a):";
instead of,
cin>>b;
cout<<"gets(a):";
gets(a);
cin>>b read just a character, leaving the rest of the input to be read by later input operation. So gets sill has something to read and don't block.
At the first cin >> b, there is no input available. You enter '132\n' (input from terminal is usually made line by line) in a buffer and just get the 1 out of it. gets reads the next characters 32 and the \n which terminates gets. It doesn't need to read something more from the terminal.
Nothing has been re-ordered.
your input from keyboard has been send only when you pressed enter. At that time, there have been enough data to execute the cin<<b, the following cout, then to complete the gets(a).
In others words, the execution of cin<<b is suspended to the reception of a char. But that char is not send to the program until you pressed 'Enter' (this is because of your terminal settings). When you press 'Enter', the first char is received by cin<<b and the remaining is buffered. cout executes, and when it is the turn of gets(a), the buffer delivers the remaining chars included the carriage return, so gets(a) completes as well, with the data you entered to complete the cin<<b instruction.
Try to simply press enter for the cin<<b to complete, then you'll see the cout, and then you will have the gets(a) waiting for your inputs.
While not really answering your question...
The idiomatic way in C++ would rather be to use getline. It's an accident of history that does not make it part of the iostream interface directly, but it really is the function to use for inputs.
Shameless plug from the website:
// getline with strings
#include <iostream>
#include <string>
int main () {
std::string str;
std::cout << "Please enter full name: ";
getline (std::cin,str);
std::cout << "Thank you, " << str << ".\n";
}
The main advantage of getline, in this version, is that it reads up until it encounters a line-ending character.
You can specify your own set of "line-ending" characters in the overload accepting a third parameter, to make it stop on commas or colons, for example.
The code isn't reordered, but std::cout is buffered so the string doesn't appear immediately on your display. Therefore gets(a) will be executed with the output still in the buffer.
You can add a <<flush after the output string to make cout flush it's buffer.
When you use std::cin, it knows how to tell std::cout to flush the buffer before the input starts, so you don't have to.