INT to STRING

P

PentiumPunk

Hey, I am trying to get a character, check its ascii value, if the ascii is
less than 100 then I append a 0 on the front of it, so it will have 3
digits. That is my aim to have a 3 digit integer to add to my hash table
that corresponds to the ascii of a letter.

i tried:

char ch;
int i, j;
string s, s2;

fin>>str; //input string from file
for(i=0;i<str.size();i++)
{
ch=str;
if(ch<100)
{ j=ch; // assigns ascii number to j
s=j;
s2="0"+s;
cout<<s2;
}
}
it just outputs 0b ("bird" is the word that is input. and since b's ascii is
98, its supposed to output 098 ). how can i fix this? Thanks in advance!
~PentiumPunk~
 
J

John Carson

PentiumPunk said:
Hey, I am trying to get a character, check its ascii value, if the
ascii is less than 100 then I append a 0 on the front of it, so it
will have 3 digits. That is my aim to have a 3 digit integer to add
to my hash table that corresponds to the ascii of a letter.

i tried:

char ch;
int i, j;
string s, s2;

str not declared.
fin>>str; //input string from file
for(i=0;i<str.size();i++)
{
ch=str;
if(ch<100)
{ j=ch; // assigns ascii number to j
s=j;


s now stores the character b since s = j does not convert b to a text string
of its ascii number.
s2="0"+s;

now you concatenate 0 and b to give you 0b.
cout<<s2;
}
}
it just outputs 0b ("bird" is the word that is input. and since b's
ascii is 98, its supposed to output 098 ). how can i fix this? Thanks
in advance! ~PentiumPunk~

Replace

s = j;
s2="0"+s;

with

ostringstream oss;
oss << j;
s=oss.str();
s2="0"+s;

Better yet, replace it with

ostringstream oss;
oss << "0" << j;
s2 =oss.str();

You may want to move the declaration of oss outside the loop.
 
K

Kevin Goodsell

PentiumPunk said:
Hey, I am trying to get a character, check its ascii value, if the ascii is
less than 100 then I append a 0 on the front of it, so it will have 3
digits. That is my aim to have a 3 digit integer to add to my hash table
that corresponds to the ascii of a letter.

The fact that you must use ASCII complicates matters - you'll have to
have some kind of table of ASCII codes in your program to look up the
correct value (since you can't count on the implementation character set
being ASCII).

Given a std::map<char, int> ascii_codes that maps characters to their
ASCII code (building the map is left as an exercise to the reader), you
can do this (assuming appropriate declarations):

fin >> str;
char f = cout.fill('0');
for (i=0; i<str.size(); ++i)
{
ch = str;
cout << setw(3) << ascii_codes[ch] << ' ';
}
cout.fill(f);

-Kevin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,142
Messages
2,570,819
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top