C++ Printing an integer derived from a string's character - c++

I'd like to print the very first number. For some reason, its printing out as 49 instead of 1...
int n = 111111251;
string s = to_string(n);
int num = s[0];
cout << num << endl;

Its printing out 49 because that is the ascii value of 1.
If you want to print out the character, just print out s[0] directly, or convert it back to an int properly. Consider the following code:
int main()
{
int n = 111111251;
string s = to_string(n);
cout << s[0] << endl;
int num = s[0];
cout << num << endl;
int num2 = s[0] - '0';
cout << num2 << endl;
return 0;
}
This prints out:
1
49
1

While doing the right thing converting an integer to a string you change the type of the first element in the string from 'char' to 'int'. That effects the output: The character representation is still '1', but the numerical value is (ASCII) 49 (Have a look at http://en.wikipedia.org/wiki/ASCII).
You probably want char character = s[0]; cout << character << endl; or int num = s[0]; cout << char(num) << endl;

49 is the ASCII value of 1.
Hope I helped,

Related

C++ Finding a string's nth character

I am trying to do my assignment for CS, but I can not find how to get a string's first character.
Example input : 5ABCD1AB1AD
Desired output: 5
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
string word;
word = argv[1];
cout << "Word: " << word << "\n";
int length = word[0];
cout << "Word's length : " << length << "\n";
for(int i = 1; i < argc; i++){
for(int j = 0; j < length; j++){
cout << argv[i][j] << "\n";
}
}
}
word[0] is a character. There is a difference between the character '5' and the number 5. If you assign a character to an int you will get the encoding value for that character.
To convert a character to its numeric value you can subtract '0', since the encoding values for the digits are consecutive.
int length = word[0] - '0';

ASCII Dec to Char in C++

I want to get every characters of ASCII in normal char. If I only put char key only, it would return dec.
My request:
char alph = //ascii dec to normal char
For example: A in dec is 65
Note: I don't have the characters, but I do have the ASCII codes in dec like 65.
because I need user input like 65
In this case you can do this:
#include <iostream>
using namespace std;
int main() {
int code;
cout << "Enter a char code:" << endl;
cin >> code;
char char_from_code = code;
cout << char_from_code << endl;
return 0;
}
This will ouput:
Enter a char code:
65
A
It seems you have misunderstood the concept.
The numerical value is always there. Whether you print it as the letter or the numerical value depends on how you print.
std::cout will print chars as letters (aka chars) so you'll need to cast it to another integer type to print the value.
char c = 'a';
cout << c << endl; // Prints a
cout << (uint32_t)c << endl; // Prints 97
cout << endl;
uint32_t i=98;
cout << i << endl;
cout << (char)i << endl;
Output:
a
97
98
b
This is the method, very simple and then just need to make your own user interface to get input dec
#include <iostream>
using namespace std;
int main() {
int dec = 65;
cout << char(dec);
cin.get();
return 0;
}
Looks like you need hex/unhex converter. See at boost, or use this bicycle:
vector<unsigned char> dec2bin( const string& _hex )
{
vector<unsigned char> ret;
if( _hex.size() < 2 )
{
return ret;
}
for( size_t i = 0; i <= _hex.size() - 2; i += 2 )
{
string two = string( _hex.data() + i, 2 );
stringstream ss( two );
string ttt = ss.str();
int tmp;
ss >> /*hex >>*/ tmp;
unsigned char c = (unsigned char)tmp;
ret.insert( ret.end(), c );
}
return ret;
}
int main()
{
string a = "65";
unsigned char c = dec2bin( a )[0];
cout << (char)c << endl;
return 0;
}

C++ Pig Latin is not working

So, I have tried and tried to make this c++ pig latin program, but it's just not working. Here is my code:
int main()
{
string tmp = "";
char a;
cout << "String: "; getline(cin, tmp);
char pigLatin[1024];
strncpy(pigLatin, tmp.c_str(), sizeof(pigLatin));
pigLatin[sizeof(pigLatin) - 1] = 0;
a = pigLatin[0];
pigLatin[sizeof(pigLatin)] = '-';
pigLatin[sizeof(pigLatin) + 1] = a;
pigLatin[sizeof(pigLatin) + 2] = 'a';
pigLatin[sizeof(pigLatin) + 3] = 'y';
for (int i = 1; i < sizeof(pigLatin); i++)
{
cout << pigLatin[i];
}
cout << endl;
system("PAUSE");
return 0;
}
When I run it, it doesn't return any runtime errors or anything, but when I enter a string it just puts the string minus the first letter and then a bunch of spaces. Does anyone know the problem?
The problem is that sizeof returns the size in bytes of the array not the length of the string it contains. In this case the result of sizeof is 1024 assuming char is 8 bits. You could always use strlen to determine the length of the string or you can eliminate the use of a naked array altogether and use std::string instead. This would decrease the size of your code significantly. Something like this...
int main()
{
cout << "String: " << flush;
string pigLatin;
getline(cin, pigLatin);
pigLatin += '-';
pigLatin += pigLatin[0];
pigLatin += "ay";
pigLatin.erase(0, 1);
cout << pigLatin << endl;
system("PAUSE");
}

Read space separated numbers from char array to separate int(s)

I have a char array (lets' say "13 314 43 12") and i want to put the first number (13) into a separate integer . how do i do that ? is there any way like splitting the first number into 10 + 3 and then adding them to the int ?
I am not sure what you mean by getting 1 and 3, but if you want to split the space-separated string into integers I suggest using a stream.
std::istringstream iss(s);
int n;
while(iss >> n)
{
std::cout << "Integer: " << n << std::endl;
}
[edit] Alternatively, you could parse the string yourself, something like this:
char* input = "13 314 43 12";
char* c = input;
int n = 0;
for( char* c = input; *c != 0; ++c )
{
if( *c == ' ')
{
std::cout << "Integer: " << n << std::endl;
n = 0;
continue;
}
n *= 10;
n += c[0] - '0';
}
std::cout << "Integer: " << n << std::endl;
#include <cstring>
#include <iostream>
#include <stdlib.h>
int main ()
{
char str[] = "13 45 46 96";
char * pch = strtok (str," ");
while (pch != NULL)
{
std::cout << atoi(pch) << "\n"; // or int smth=atoi(pch)
pch = strtok (NULL, " ");
}
return 0;
}
If you just want the first number, just use a function like atoi() or strtol(). They extract a number until it runs into the null terminated character or a non-numeric number.
According to your question I think following code will give some idea.
#include <string>
#include <iostream>
using namespace std;
int main(){
char s[] = "13 314 43 12";
//print first interger
int v = atoi(s);
cout << v << std::endl;
//print all integer
for (char c : s){
if (c == ' ' || c == '\0'){
}else{
int i = c - '0';
cout << i << std::endl; // here 13 print as 1 and 3
}
}
}
If you want to print first number you can use
int v = atoi(s);
cout << v << std::endl;
If you want to split and print all integers Ex: 13 as 1,3
for (char c : s){
if (c == ' ' || c == '\0'){
}else{
int i = c - '0';
cout << i << std::endl; // here 13 print as 1 and 3
}
}

Bit Operations, mainly ~

I am currently converting decimal to binary, making sure it is 8 bits. All bit operations work except the ~ (NOT) operations. They come out as a huge integer value. I am not sure why, since the other bit operations work. Here is my code: (The commented out lines are what is not working)
Edit: If I want to get 8 bit binary strings, what do I do? Use unsigned chars? If I change all unsigned ints to unsigned chars then my BinaryToDecimal function produces incorrect binary conversion.
#include <iostream>
#include <string>
using namespace std;
string BinaryToDecimal(unsigned int dec)
{
string binary = "";
float remainder = 0.0f;
while( dec != 0 )
{
remainder = dec % 2;
dec /= 2;
if( remainder == 0 )
binary.append("0");
else
binary.append("1");
}
// Reverse binary string
string ret = string(binary.rbegin(), binary.rend());
return ret;
}
int main()
{
unsigned int a = 0;
unsigned int b = 0;
cout << "Enter a number to convert to binary: ";
cin >> a;
cout << "Enter a number to convert to binary: ";
cin >> b;
cout << "A = " << BinaryToDecimal(a) << endl;
cout << "B = " << BinaryToDecimal(b) << endl;
unsigned int c = a & b;
unsigned int d = a | b;
//unsigned int e = ~a;
//unsigned int f = ~b;
unsigned int g = a ^ b;
unsigned int h = a << 2;
unsigned int i = b >> 3;
cout << "A & B = " << BinaryToDecimal(c) << endl;
cout << "A | B = " << BinaryToDecimal(d) << endl;
//cout << "~A = " << BinaryToDecimal(e) << endl;
//cout << "~B = " << BinaryToDecimal(f) << endl;
cout << "A ^ B = " << BinaryToDecimal(g) << endl;
cout << "A << 2 = " << BinaryToDecimal(h) << endl;
cout << "B >> 3 = " << BinaryToDecimal(i) << endl;
}
If you perform a binary NOT on a small unsigned integer, you will get a large number as a result, seeing as most of the most significant bits will be set to 1 (the inverse of what they were in the operand).
In this case you're doing ~ 0 which will certainly give you a large number, in fact the largest possible unsigned int, since all bits will be set to 1.
(What result were you expecting?)
You are using an unsigned int for the operations, such that the inversion of small number becomes a large number because of leading 1 starting from the MSB. If you only want the representation is 8 bit only, you should use unsigned char for its storage.
But you cannot change a or b to unsigned char. Otherwise, cin >> a will put the number's ASCII code to a, not a number. For example, your input is 5, it puts 0x35 ('5'), not number 5.
If you don't want to change unsigned int of your code, you can do some minor enhancements
string BinaryToDecimal(unsigned int dec)
{
string binary = "";
float remainder = 0.0f;
dec &= 0xff; // only 8 bits you care about
while( dec != 0 )
{
....
But you are using while( dec !=0 ), which is buggy. If the result is already 0, then the function returns an empty string, not "0000". Instead, you should use a counter to count only for 8 bit.
for (int i = 0; i < 8; i++ ) {
if ((dec & 1) != 0)
binary.append("1");
else
binary.append("0");
dec >>= 1;
}
Also, using bit wise AND to test the bit is 0 or 1, and shift operation, is better than / and % operators.
Finally, for 8 bit 5 (0000_0101), its inversion is 250 (1111_1010), not 1010.