This question already has answers here:
Why does subtracting '0' in C result in the number that the char is representing?
(8 answers)
Closed 2 years ago.
I'm trying to figure out a code that a friend sent me and I couldn't figure out why this certain code exists.
The goal is that when you type a 3 digit number sequence in string, it converts it to int and prints the sequence in reverse.
string s;
cout <<"enter integer sequence";
cin >> s;
int firstdig, seconddig, thirddig;
firstdig = s[0];
seconddig = s[1];
thirddig = s[2];
cout << thirddig << seconddig << firstdig;
Here is the problem with this code
When I input "123", the output becomes "515049" instead of "321"
However
This is the code that apparently fixes the problem
string s;
cout <<"enter integer sequence";
cin >> s;
int firstdig, seconddig, thirddig;
firstdig = s[0] - '0';
seconddig = s[1] - '0';
thirddig = s[2] - '0';
cout << thirddig << seconddig << firstdig;
This time, I input "123", the output becomes "321"
My main question is, where did "515049" come from, and what does the code "- '0'" do?
I don't know what that code does. C++ C++ C++
In the first code, you are converting a char into an int directly which, as it has been pointed out in the comments, gets the ASCII value of the characters.
In the second code, when you substract the ASCII value of the characters and '0' you get the original value of the character.
Related
This question already has answers here:
String plus Char - what is happening?
(5 answers)
C++. Why std::cout << char + int prints int value?
(2 answers)
cout and String concatenation
(3 answers)
How object cout prints multiple arguments?
(4 answers)
Closed 10 months ago.
I was experimenting with a statement in C++ using online compilers. When I try to run this specific code
cout << num[i] + " " + num[i];
The online compilers give no output. I can change the + symbol to << but I want to know the reason that the code does not give any output on these online compilers.
Online compilers that I tried are onlinegdb, programiz, and jdoodle.
#include <iostream>
#include <string>
int main() {
std::string num = "123";
int i = 0;
std::cout << num[i] + " " + num[i];
return 0;
}
C++ is not like JavaScript or many higher-level languages, as in you may not delimit you data with +'s or ,'s. As shown in Lewis' answer, each item you wish to have printed must be separated by an insertion delimiter (<<). As for extracting, you may use the extraction delimiter (>>).
In your case, you are doing mathematical operations on the the characters themselves (adding together their numerical ASCII representations together, which could print unprintable and invisible characters). The printable ASCII characters range from 32 (space character) to 127 (delete character) (base 10). When summing '1' + ' ' + '1' you are left with (49 + 32 + 49) or (130) which exceeds the printable character range. Or you may also be accessing garbage as #pm100 said in the comments due to pointer arithmetic.
Here is an example of using the insertion operator:
#include <iostream>
int main(void) {
int some_int = 1;
std::cout << "this is my " << some_int << "st answer on StackOverflow :)"
<< std::endl;
return 0;
}
And as for the extraction operator:
#include <iostream>
int main(void) {
int num;
std::cout << "Enter an integer: ";
std::cin >> num; // stores the input into the `num` variable
std::cout << "The number is: " << num << std::endl;
return 0;
}
Pointer arithmetic:
const char* get_filename(const char* _path, size_t _offset) {
return (_path + _offset);
}
// This is an example
//
// path = "path/to/my/file/file.txt";
// offset ^ ^
// 0 |
// + 16 ------------|
// path = "file.txt";
This question already has answers here:
How to output a character as an integer through cout?
(6 answers)
Convert an int to ASCII character
(11 answers)
Closed 3 years ago.
I have a program that takes a string. Using the check() function that calculate the sum of all the value in the string of integers, I make additional computations, aka ss. The issue comes when I try to convert ss, which is an int, into a char, c.
When I try to print out the newly converted value, nothing prints out on the console, not even an error message.
I have tried using static_cast<char>(ss), and it won't work. Yet when I try to print out the ss value, I get it to print it out.
Source Code
void sum(string input)
{
int s = check(input);
int ss = (s * 9) % 10;
char c = ss;
cout << "val is: " << c << endl;
}
int main()
{
string x = "7992739871";
sum(x);
return 0;
}
Can someone explain what I might be doing wrong and how it can be fixed?
You can use std::to_string() (C++11) but making sure that the value of c is something that can be printable is a better practice.
This question already has answers here:
C++ handling very large integers
(15 answers)
Closed 3 years ago.
I am supposed to get two big integer numbers (up to 600 digits) from console screen and write the result on the console again.
I defined two variables of type std::string to store two big integer numbers .I take their values from the user. To take the sum of that two numbers, I defined two vectors to store the digits of that two strings of numbers .
Here is the problem, when I try to loop through the vector to print the digits that I took from strings of numbers I get the following result .The Ascii values of the digits are printed on The Console.
Could anyone tell me how to fix this problem please.
Note: The code is still not complete .
For the first string I took the numbers 9 8 7 6 5 4 3 2 1 from the user , on the console window I got the following result.
[0]57
[1]56
[2]55
[3]54
[4]53
[5]52
[6]51
[7]50
[8]49
#include <iostream>
#include <sstream>
#include <vector>
#include <algorithm>
std::string Sum_Of_Two_Long_Integers()
{
std::string First_String ;
std::string Second_String ;
std::string Result_String ;
std::cout << "Please enter the first number: " ;
std::getline(std::cin, First_String);
std::cout << "Please enter the second number: " ;
std::getline(std::cin, Second_String);
std::vector <int> First_String_Vector (First_String.length()) ;
std::vector <int> Second_String_Vector (Second_String.length()) ;
for(int Counter = 0 ; Counter < First_String_Vector.size() ; ++ Counter)
{
First_String_Vector[Counter] = First_String[Counter] ;
Second_String_Vector[Counter] = Second_String[Counter] ;
std::cout << "[" << Counter << "]" << First_String_Vector[Counter] << std::endl ;
}
return Result_String ;
}
int main()
{
std::string Result_String = Sum_Of_Two_Long_Integers() ;
std::cout << "Result = " << Result_String << std::endl ;
return 0 ;
}
First_String_Vector[Counter] = First_String[Counter] ;
Second_String_Vector[Counter] = Second_String[Counter] ;
The digits are stored as ASCII in you string, you should convert to integer before placing them into the vector.
This would do the trick:
First_String_Vector[Counter] = First_String[Counter] - '0';
Second_String_Vector[Counter] = Second_String[Counter] - '0';
I would also add a check for valid input before populating your vectors to make sure that you only read digits:
if(First_String[Counter] < '0' || First_String[Counter] > '9' ||
Second_String[Counter] < '0' || Second_String[Counter] > '9')
{
std::cout << "Invalid input\n";
return "":// Or better throw an exception
}
EDIT: '6' isn't equal to 6. The first one is a char, its value is ASCII for character '6', and the second is the integer 6.
ASCII is an encoding. Characters are mapped to some numbers. Value for '0' is 48, '1' is 49, ..., '9' is 57
To be even more precise C++ does not guarantee to use ASCII encoding (though I don't know of an implementation that does not use it), but it does guarantee that '0'...'9' have contiguous integer values. So '6' - '0' will give us integer 6.
This question already has answers here:
Cout a whole array in c++
(7 answers)
Closed 3 years ago.
I'm trying to implement a function that will parse numbers for a calculator assignment that I have been given. A for loop has been set up that will iterate through each index in the input array which is a arithmetic equation e.g "1+2+3+4+5". I created a function isDigit() that will return true or false if the character is between 0 and 9. This is how I am parsing the numbers. My problem is that the numbers are not being permanently stored in my numbers[] array which I would like to return.
Currently the numbers are being printed to the console with the first cout as "12345" but with the second cout (currently commented) which to check what my returned array stores is an ambiguous hex number. Can someone please help me to return "12345" in numbers[].
int * parseNumbers(char input[])
{
static int numbers[10];
for (int i = 0; i < strlen(input); i++)
{
if (isDigit(input[i]))
{
numbers[i] = input[i] - '0';
cout << numbers[i];
}
}
//cout << numbers << endl;
return(numbers);
}
numbers = 1, 2, 3, 4, 5
currently getting numbers = 002D26E8
I think what you're looking for is atoi to convert char to int.
Instead of using numbers[i] = input[i] - '0';
try this:
numbers[i] = atoi(input[i]);
Make sure to have #include <stdlib.h> if not aready added
Reference: http://www.cplusplus.com/reference/cstdlib/atoi/
i'm currently learning c++ and have a project that I'm currently working on. My program in its entirety is to randomize 3 numbers from values 0-9 or set them myself. I was able to get the randomize numbers to work but not the setting of numbers myself. The issue being that when i tried to have the numbers as the int data type it produced 3 numbers for one input. It should be that x = 1, y = 2, z =3.... vales are: 123. To counter this issue I made the data type a character instead but it bugs me that random numbers are int values and my set numbers are char values. This is my current code below:
if ( userInput == 's') {
cout << "Enter three distinct digits each in the range 0..9 (e.g. 354)";
char num1 = ' ';
char num2 = ' ';
char num3 = ' ';
cin >> num1 >> num2 >> num3;
cout << endl << "Values to guess are: " << num1 << num2 << num3;
This might help you understand better what you're looking for.
Consider for example using:
int x;
cin >> x; // read an integer from the standard input stream (ignoring initial white space)
This will read a single integer from standard in, while
char c;
cin >> c; // read a character from standard input stream (ignoring initial white space)
read a single character from standard in (generally an ASCII character value).
If you have the following in standard input:
354
the first will finish with x = 354 and the second with c = '3' // = 51.
From my understanding you want to read 3 digits from standard in and store them in 3 separate numeric data types. You can do this using the following code:
uint8_t get_digit() {
char c;
cin >> c; // read a single non-whitespace character
if (! is_digit(c) ) return -1; // Error did not read a digit return bogus number
return (uint8_t)(c - '0'); // convert ascii digit to number and return value
}
This code will read a single character and check if it was a digit, if not it returns a bogus result (-1) othewise it returns the numeric value of the digit.