Get String from Getline method in C++

Hello,

I want to get a string from input but seems 'Enter' instead of an input string in num variable.



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
#include <iostream>
#include <math.h>
#include <string>
using namespace std;

int Convert(char a)
{
	if (a <= '9' && a >= '0')
		return (int)a - 48;
	return (int)a - 65 + 10;
}


int main()
{
	{
		int NUM;
		int TEN = 0;
		int i = 0;
		int TO[100];
		int from;
		cout << "Base from? \n";
		cin >> from;

		int to;
		cout << "Base to? \n";
		cin >> to;

		string num;
		cout << "Enter Number: \n";
		getline(cin,num); //!!

		cout << num;

	}


}

getline() stops when it finds a '\n' on the input
you pressed <Enter> after the number, so the string is empty

you need to discard the '\n'

getline(cin>>ws, num);
https://en.cppreference.com/w/cpp/io/manip/ws
Last edited on
You could also just do cin >> num;

Don't use magic constants in convert():
1
2
3
4
5
6
int Convert(char a)
{
	if (a <= '9' && a >= '0')
		return (int)a - '0';
	return (int)a - 'A' + 10;
}
@dhayden
Thank you but we cannot because in Hexadecimal we have for example 3C1 and we should convert C to 12

So we should get Hexa in a string variable.
Thank you but we cannot because in Hexadecimal we have for example 3C1 and we should convert C to 12
My suggested change will do that. In fact, the only difference between your Convert() and mine is that I used some character constants instead of magic numbers.

So we should get Hexa in a string variable.
I understand that. Your program has:
string num;
and I am suggesting that you read it with:
cin >> num;
Topic archived. No new replies allowed.