Jul 3, 2018 at 4:27pm Jul 3, 2018 at 4:27pm UTC
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
Jul 3, 2018 at 4:38pm Jul 3, 2018 at 4:38pm UTC
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 Jul 3, 2018 at 4:39pm Jul 3, 2018 at 4:39pm UTC
Jul 3, 2018 at 6:08pm Jul 3, 2018 at 6:08pm UTC
Thank you for your answer!
Jul 3, 2018 at 10:32pm Jul 3, 2018 at 10:32pm UTC
Using floating-point variables to store money is a bad habit. Just sayin'.