lilroo
lilroo

Reputation: 3148

How to display an integer literally as a character

I have an integer 1 and i want to display it as a character '1' in C++. So far I have only managed to convert it from say integer 65 to character 'A'. How do you stop this ?

Upvotes: 2

Views: 3689

Answers (4)

Joel Rondeau
Joel Rondeau

Reputation: 7586

You did just ask about printing an integer, so the really simple c++ answer is:

#include <iostream>

int main()
{
  int value = 1;
  std::cout << value << endl;
  return 0;
}

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126867

int theDigit = 1;
char ch = theDigit+'0';

This works because it's guaranteed1 that the sequence of characters '0'...'9' is contiguous, so if you add your number to '0' you get the corresponding character. Obviously this works only for single digits (if theDigit is e.g. 20 you'll get an unrelated character), if you need to convert to a string a whole number you'll need snprintf (in C) or string streams (in C++).


  1. C++11, [lex.charset] ¶3:

In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

By the way, I suppose that they didn't mandate contiguity also in the alphabetical characters just because of EBCDIC.

Upvotes: 5

riptide464c
riptide464c

Reputation: 176

#include <stdio.h>
#include <stdlib.h>

int i = 3;
char buffer [25];
itoa (i, buffer, 10);
printf ("Integer: %s\n",buffer);

Integer: 3

Upvotes: 1

GILGAMESH
GILGAMESH

Reputation: 1856

Use the stringstream.

int blah = 356;
stringstream ss;
string text;

ss << blah;
ss >> text;

Now text contains "356"(without quotes). Make sure to include the header files and use the namespace if you are going to copy my code:

#include <sstream> //For stringstream
#include <string>

using namespace std;

Upvotes: 2

Related Questions