Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 800
Thomas Boxley Avatar asked Mar 04 '13 19:03

Thomas Boxley


People also ask

How do you stop going to the next line in C++?

to flush: use std::flush. to newline: use '\n' or append it to your string: "foobar!\ n" both: use std::endl.

Does CIN go to next line?

In the line “cin >> c” we input the letter 'Z' into variable c. However, the newline when we hit the carriage return is left in the input stream. If we use another cin, this newline is considered whitespace and is ignored.

How can I take input from a single line in C++?

The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.

How do you enter a variable in C++?

Standard input (cin) In most program environments, the standard input by default is the keyboard, and the C++ stream object defined to access it is cin . int age; cin >> age; The first statement declares a variable of type int called age , and the second extracts from cin a value to be stored in it.


1 Answers

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.

like image 101
Benjamin Lindley Avatar answered Oct 17 '22 22:10

Benjamin Lindley