cout after cin

How to print text immediately after cin, for example if I wrote code like:

int x;
cout << "Enter your amount of money: ";
cin >> x;
cout << " dollars";


it will print:
Enter your amount of money: x // I want to put here dollars
dollars


This isn't an issue with C++ libraries specifically, that's simply how the console works; user input + enter creates a newline. You have to use a custom console library (such as Curses).

See: http://www.cplusplus.com/forum/beginner/32834/ or https://stackoverflow.com/questions/15209370/how-do-i-input-variables-using-cin-without-creating-a-new-line

If you are on Windows, check out the following example, copied from the above link.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

#include <windows.h>
#include <iostream>
#include <string>
using namespace std;

void SetCursor(int x, int y)
{
    HANDLE console=GetStdHandle(STD_OUTPUT_HANDLE);
    COORD pos;

    pos.X=x;
    pos.Y=y;

    SetConsoleCursorPosition(console,pos);
}

void GetCursor(int & x, int & y)
{
    HANDLE console=GetStdHandle(STD_OUTPUT_HANDLE);
    CONSOLE_SCREEN_BUFFER_INFO csbi;

    GetConsoleScreenBufferInfo(console,&csbi);

    x=csbi.dwCursorPosition.X;
    y=csbi.dwCursorPosition.Y;
}

int main()
{
    string name;
    int x,y;

    cout<<"Enter your name: ";
    getline(cin,name);

    GetCursor(x,y);

    y--;
    x=18+name.size();

    SetCursor(x,y);

    cout<<"Name entered\n";

    cin.get();
    return 0;
}
Last edited on
Thank you for your answer!
closed account (E0p9LyTq)
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
   int x;

   std::cout << "Enter your amount of money: ";
   std::cin >> x;

   std::cout << "\n$" << x <<" dollars.\n";
}

Enter your amount of money: 125

$125 dollars.

You could refine the variable to be a float/double so you can enter dollars and cents, and improve the output to show two decimal places even when there aren't two.
Using floating-point variables to store money is a bad habit. Just sayin'.
Topic archived. No new replies allowed.