Why is my output different from input? (C++) - c++

Input : 7182933164
Output : 2147483647
(it isnt all of the code i know there are missing } )
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream file("Numbers.txt");
int num;
cout << "Enter credit card number : " << endl;
cin >> num;
cout << "enterned : " << num << endl;

Use std:: string to represent code numbers instead.

The value 7182933164 is such a huge number that it crosses the value of the integer it could holds (i.e. -2147483648 to 2147483647). Use long type modifier to accept such values. And if there's only positive integer required, added unsigned before long.
Do something like:
...
long num; // dependent upon the computer architecture
...
If that doesn't works, try long long. Although it's working fine in OnlineGDB (example).

Related

Finding Average of two numbers C++ [duplicate]

This question already has answers here:
Printing the correct number of decimal points with cout
(13 answers)
Closed 1 year ago.
As a newbie in the world of programming, I have to write a bit of C++ code to find the average of two numbers.
However, my code somehow appears to be incorrect. Please take a look at my code:
#include <iostream>
using namespace std;
int main() {
float a, b, average;
cin >> a;
cin >> b;
average = (a+b)/2;
cout << average << endl;
}
however, it says I am wrong because when I input 10 10 it outputs 10 but the system wants me to output 10.00
You need to use some I/O manipulators.
std::setprecision and std::fixed
Example:
#include <iomanip>
#include <iostream>
int main() {
if(float a, b; std::cin >> a >> b) {
float average = (a+b)/2;
std::cout << std::fixed << std::setprecision(2) << average << '\n';
}
}
Like others have said you need to change your cout line to:
cout << fixed << setprecision(2) << average << endl;
Remember that with the <<s you're putting a stream of data (an iostream) into cout. The first piece of data is std::fixed which says "Display floats to a fixed number of decimal places, don't cut off any trailing zeros." And then std::setprecision(2) says "Make that fixed number of decimal places 2." You could use an int variable or another number in place of 2 if you wanted. From there the stream has your average and an endline like before.
Set decimal precision
Sets the decimal precision to be used to format floating-point values on output operations.
#include <iostream>
using namespace std;
#include <iomanip> // std::setprecision
int main() {
float a, b, average;
cin >> a;
cin >> b;
average = (a+b)/2;
cout << fixed << setprecision(2) << average << endl;
}

How to convert char(or string, other type) -> bits?

In c++,
I don't understand about this experience. I need your help.
in this topic, answers saying use to_string.
but they say 'to_string' is converting bitset to string and cpp reference do too.
So, I wonder the way converting something data(char or string (maybe ASCII, can convert unicode?).
{It means the statement can be divided bit and can be processed it}
The question "How to convert char to bits?"
then answers say "use to_string in bitset"
and I want to get each bit of my input.
Can I cleave and analyze bits of many types and process them? If I can this, how to?
#include <iostream>
#include <bitset>
#include <string>
using namespace std;
int main() {
char letter;
cout << "letter: " << endl;
cin >> letter;
cout << bitset<8>(letter).to_string() << endl;
bitset<8> letterbit(letter);
int lettertest[8];
for (int i = 0; i < 8; ++i) {
lettertest[i] = letterbit.test(i);
}
cout << "letter bit: ";
for (int i = 0; i < 8; ++i) {
cout << lettertest[i];
}
cout << endl;
int test = letterbit.test(0);
}
When executing this code, I get result I want.
But I don't understand 'to_string'.
An important point is using of "to_string"
{to_string is function converting bitset to string(including in name),
then Is there function converting string to bitset???
Actually, in my code, use the function with a letter -> convert string to bitset(at fitst, it is result I want)}
help me understand this action.
Q: What is a bitset?
https://www.cplusplus.com/reference/bitset/bitset/
A bitset stores bits (elements with only two possible values: 0 or 1,
true or false, ...).
The class emulates an array of bool elements, but optimized for space
allocation: generally, each element occupies only one bit (which, on
most systems, is eight times less than the smallest elemental type:
char).
In other words, a "bitset" is a binary object (like an "int", a "char", a "double", etc.).
Q: What is bitset<>.to_string()?
Bitsets have the feature of being able to be constructed from and
converted to both integer values and binary strings (see its
constructor and members to_ulong and to_string). They can also be
directly inserted and extracted from streams in binary format (see
applicable operators).
In other words, to_string() allows you to convert the binary bitset to text.
Q: How to to I convert convert char(or string, other type) -> bits?
A: Per the above, simply use bitset<>.to_ulong()
Here is an example:
https://en.cppreference.com/w/cpp/utility/bitset/to_string
Code:
#include <iostream>
#include <bitset>
int main()
{
std::bitset<8> b(42);
std::cout << b.to_string() << '\n'
<< b.to_string('*') << '\n'
<< b.to_string('O', 'X') << '\n';
}
Output:
00101010
**1*1*1*
OOXOXOXO

Manually converting a char to an int - Strange behaviour

I've wrote a small program to convert a char to an int. The program reads in chars of the form '1234' and then outputs the int 1234:
#include <iostream>
using namespace std;
int main(){
cout << "Enter a number with as many digits as you like: ";
char digit_char = cin.get(); // Read in the first char
int number = digit_char - '0';
digit_char = cin.get(); // Read in the next number
while(digit_char != ' '){ // While there is another number
// Shift the number to the left one place, add new number
number = number * 10 + (digit_char - '0');
digit_char = cin.get(); // Read the next number
}
cout << "Number entered: " << number << endl;
return 0;
}
This works fine with small chars, but if I try a big char (length 11 and above) like 12345678901 the program returns the wrong result, -539222987.
What's going on?
12345678901 in binary is 34 bits. As a result, you overflowed the integer value and set the sign bit.
Type int is not wide enough to store such big numbers. Try to use unsigned long long int instead of the type int.
You can check what maximum number can be represented in the given integer type. For example
#include <iostream>
#include <limits>
int main()
{
std::cout << std::numeric_limits<unsigned long long int>::max() << std::endl;
}
In C you can use constant ULLONG_MAX defined in header <limits.h>
Instead of using int, try to use unsigned long long int for your variable number.
That should solve your problem.
Overflowed integer. Use unsigned long long int.

Exceeding C++'s largest integer datatype

I am writing a combinations calculator and for the bigger calculations I end up hitting an overflow with long long int or int64_t. Is it possible to perhaps, at least, convert the number to something of this sort: 6.7090373691429E+19?
Here is my code:
#include <iostream>
#include <string.h>
#include <math.h>
int main() {
std::string charset;
int i, length; int64_t total = 0;
std::cout << "Charset: ";
std::cin >> charset;
std::cout << "Length: ";
std::cin >> length;
for (i=0;i<(length+1);i++) {
total += pow(charset.size(),i);
}
std::cout << "\nPossible combinations: " << total << std::endl;
return 0;
}
The C++ standard library does not include arbitrary size integer types.
You can use Boost Multiprecision for this. It has different backends, using dedicated libraries (e.g. GMP) and a custom backend without external dependencies (cpp_int).
Edit: To be fair, vsoftco already mentioned Boost Multiprecision in a comment.

How to force a preceding 0 to an int (without actually outputting it)

So I'm trying to force a preceding 0 to an int so it can be processed later on. Now, all the tutorials i've seen on SO, or any other website, all use something similar to this:
cout << setfill('0') << setw(2) << x ;
Whilst this is great, i can only seem to get it to work with cout, however, I don't want to output my text, i just want the number padded, for later use.
So far, this is my code..
#include <iostream>
#include <string>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <sstream>
/*
using std::string;
using std::cout;
using std::setprecision;
using std::fixed;
using std::scientific;
using std::cin;
using std::vector;
*/
using namespace std;
void split(const string &str, vector<string> &splits, size_t length = 1)
{
size_t pos = 0;
splits.clear(); // assure vector is empty
while(pos < str.length()) // while not at the end
{
splits.push_back(str.substr(pos, length)); // append the substring
pos += length; // and goto next block
}
}
int main()
{
int int_hour;
vector<string> vec_hour;
vector<int> vec_temp;
cout << "Enter Hour: ";
cin >> int_hour;
stringstream str_hour;
str_hour << int_hour;
cout << "Hour Digits:" << endl;
split(str_hour.str(), vec_hour, 1);
for(int i = 0; i < vec_hour.size(); i++)
{
int_hour = atoi(vec_hour[i].c_str());
printf( "%02i", int_hour);
cout << "\n";
}
return 0;
}
The idea being to input an int, then cast it to a stringstream to be split into single characters, then back to an integer. However, anything less than the number 10 (<10), I need to be padded with a 0 on the left.
Thanks guys
EDIT:
The code you see above is only a snippet of my main code, this is the bit im trying to make work.
Alot of people are having trouble understanding what i mean. so, here's my idea. Okay, so the entire idea of the project is to take user input (time (hour, minute) day(numeric, month number), etc). Now, i need to break those numbers down into corresponding vectors (vec_minute, vec_hour, etc) and then use the vectors to specify filenames.. so like:
cout << vec_hour[0] << ".png";
cout << vec_hour[1] << ".png";
Now, i know i can use for loops to handle the output of vectors, i just need help breaking down the input into individual characters. Since i ask users to input all numbers as 2 digits, anything under the number 10 (numbers preceding with a 0), wont split into to digits because the program automatically removes its preceding 0 before the number gets passed to the split method (ie. you enter 10, your output will be 10, you enter 0\n9, and your output will be a single digit 9). I cant have this, i need to pad the any number less than 10 with a 0 before it gets passed to the split method, therefore it will return 2 split digits. I cast the integers into stringstreams because thats the best way for splitting data types i found (incase you were wondering).
Hope i explained everything alot better :/
If I understand correctly your question, you can just use those manipulators with a stringstream, for instance:
std::stringstream str_hour;
str_hour << setfill('0') << setw(2) << int_hour;
String streams are output streams, so I/O manipulators affect them the same way they affect the behavior of std::cout.
A complete example:
#include <sstream>
#include <iostream>
#include <iomanip>
int main()
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << 10; // Prints 10
ss << " - ";
ss << std::setfill('0') << std::setw(2) << 5; // Prints 05
std::cout << ss.str();
}
And the corresponding live example.
int and other numeric types store values. Sticking a 0 in front of an integer value does not change the value. It's only when you convert it to a text representation that adding a leading 0 changes what you have, because you've changed the text representation by inserting an additional character.
X-Y Problem, I think
for ( int i = 0; i < POWER_OF_TEN; i++ )
{
vector<int>.push_back(num%10);
num /= 10
}
?
Then reverse the vector if you want
yes i know this is not real code
if you really want characters, vector<char>.push_back(num%10 + '0')?