Why does cin fail, when I enter a number like: 3999999999 but it works for smaller numbers like: 5 ?
#include <iostream>
int main()
{
int n;
std::cin >> n;
if (std::cin.fail())
std::cout << "Something sucks!";
else
std::cout << n;
return 0;
}
Try:
std::cout << std::numeric_limits<int>::max() << std::endl; // requires you to #include <limits>
int on your system is likely a 32-bit signed two's complement number, which means the max value it can represent is 2,147,483,647. Your number, 3,999,999,999, is larger than that, and can't be properly represented by int. cin fails, alerting you of the problem.
long may be a 64-bit integer on your system, and if it is, try that. You need a 64-bit integer to represet 3,999,999,999. Alternatively, you can use an unsigned int, which will be able to represent numbers as large as 4,294,967,295 (again, on the typical system). Of course, this means you can't represent negative numbers, so it's a trade-off.
That's probably because the big value is too big to fit into a variable of int type on your system. Try just assigning the big value to your variable and see what happens.
To fix it, change the type of the variable to a wider type, like long or long long.
The maximal number representable by an int depends on the number of bits it is represented. Usually, it's 32-bits, ie. the maximal number is 2147483647, which is smaller than the number you typed.
When the formatted input functions fail in some form, they set std::ios_base::failbit and leave the original value in the argument unchanged. There are different failures and overflows are considered one sort of failure. I recall a discussion about different errors being indicated in different ways but I din't recall the outcome. The best bet may be to make sure errno is cleared before calling any of the input functiins and checking errno for ERANGE to distinguish an overflow from a format error.
Related
Why does cin fail, when I enter a number like: 3999999999 but it works for smaller numbers like: 5 ?
#include <iostream>
int main()
{
int n;
std::cin >> n;
if (std::cin.fail())
std::cout << "Something sucks!";
else
std::cout << n;
return 0;
}
Try:
std::cout << std::numeric_limits<int>::max() << std::endl; // requires you to #include <limits>
int on your system is likely a 32-bit signed two's complement number, which means the max value it can represent is 2,147,483,647. Your number, 3,999,999,999, is larger than that, and can't be properly represented by int. cin fails, alerting you of the problem.
long may be a 64-bit integer on your system, and if it is, try that. You need a 64-bit integer to represet 3,999,999,999. Alternatively, you can use an unsigned int, which will be able to represent numbers as large as 4,294,967,295 (again, on the typical system). Of course, this means you can't represent negative numbers, so it's a trade-off.
That's probably because the big value is too big to fit into a variable of int type on your system. Try just assigning the big value to your variable and see what happens.
To fix it, change the type of the variable to a wider type, like long or long long.
The maximal number representable by an int depends on the number of bits it is represented. Usually, it's 32-bits, ie. the maximal number is 2147483647, which is smaller than the number you typed.
When the formatted input functions fail in some form, they set std::ios_base::failbit and leave the original value in the argument unchanged. There are different failures and overflows are considered one sort of failure. I recall a discussion about different errors being indicated in different ways but I din't recall the outcome. The best bet may be to make sure errno is cleared before calling any of the input functiins and checking errno for ERANGE to distinguish an overflow from a format error.
In an attempt to verify (using VS2012) a book's claim (2nd sentence) that
When we assign an integral value to an object of floating-point type, the fractional part is zero.
Precision may be lost if the integer has more bits than the floating-point object can accommodate.
I wrote the following wee prog:
#include <iostream>
#include <iomanip>
using std::cout;
using std::setprecision;
int main()
{
long long i = 4611686018427387905; // 2^62 + 2^0
float f = i;
std::streamsize prec = cout.precision();
cout << i << " " << setprecision(20) << f << setprecision(prec) << std::endl;
return 0;
}
The output is
4611686018427387905 4611686018427387900
I expected output of the form
4611686018427387905 4611690000000000000
How is a 4-byte float able to retain so much info about an 8-byte integer? Is there a value for i that actually demonstrates the claim?
Floats don't store their data in base 10, they store it in base 2. Thus, 4611690000000000000 isn't actually a very round number. It's binary representation is:
100000000000000000000111001111100001000001110001010000000000000.
As you can see, that would take a lot of data to precisely record. The number that's actually printed, however, has the following binary representation:
11111111111111111111111111111111111111111111111111111111111100
As you can see, that's a much rounder number, and the fact that it's off by 4 from a power of two is likely due to rounding in the convert-to-base-10 algorithm.
As an example of a number that won't fit in a float properly, try the number you expected:
4611690000000000000
You'll notice that that will come out very differently.
The float retains so much information because you're working with a number that is so close to a power of 2.
The float format stores numbers in basically binary scientific notation. In your case, it gets stored as something like
1.0000000...[61 zeroes]...00000001 * 2^62.
The float format can't store 62 decimal places, so the final 1 gets cut off... but we're left with 2^62, which is almost exactly equal to the number you're trying to store.
I'm bad at manufacturing examples, but CERT isn't; you can view an example of what happens with bungled number conversions here. Note that the example is in Java, but C++ uses the same floating point types; additionally, the first example is a conversion between a 4-byte int and a 4-byte float, but this further proves your point (there's less integer information that needs to be stored than there is in your example, yet it still fails).
I am trying to solve a this problem-> Candy3
We are supposed to use long long to solve this problem. But when I'm using cin to take inputs that are larger than 10^19 (i know it is the limit of long long but the there is limit constraint specified and we are supposed to output the right answer) it is giving random outputs. Whereas, when I'm using scanf() it is printing the correct answer.
This is really weird. What is the difference b/w scanf and cin.
My code
#include<iostream>
#include<stdio.h>
using namespace std;
int main(){
int t,n;
cin>>t;
while(t--){
long long sum=0,sweet;
cin>>n;
for(int i=0; i<n; i++){
//cin>>sweet; printing yes no randomly
scanf("%lld", &sweet); // working correctly
sum = (sum + sweet)%n;
}
if(sum)
cout<<"NO"<<endl;
else
cout<<"YES"<<endl;
}
return 0;
}
EDIT: This is a weird question and it is not specified in the question that what should be the size of input. Here is the input specification -
"The first line of the input file contains an integer T specifying the
number of test cases. Each test case is preceded by a blank line. Each
test case looks as follows: The first line contains N : the number of
children. Each of the next N lines contains the number of candies one
child brought."
As many people have noted, you're attempting to read integers which will overflow a long long.
The difference between scanf and cin.operator>>() with respect to integer overflow is that scanf does not (necessarily) test for integer overflow; if the number read is too big, the result is undefined behaviour. It's common that you'll just find an incorrect value in the corresponding argument, but there are no guarantees.
cin.operator>>(), on the other hand, does check for integer overflow, and if it finds integer overflow, it stores the largest possible integer of the indicated type and puts the cin stream into failure state. Once the stream is in failure state, it stays there until the state is cleared; furthermore, any subsequent use of cin.operator>>() will do nothing if the stream is in failure state.
Consequently, once you attempt to read an integer which is too large with cin.operator>>(), your code will find sweet to be the largest possible long long on every subsequent read.
So when using C++ formatted input, you need to always check for failure, and do something appropriate.
You say you're entering values bigger than 1019. That will probably overflow a long long.
Type long long is guaranteed to be at least 64 bits wide, and on every compiler I've seen it's exactly 64 bits wide. That means the maximum possible value of a long long is 263-1, or 9,223,372,036,854,775,807, which is approximately 9 * 1018.
If you enter a value of 1019, or 10,000,000,000,000,000, it will overflow. If cin << ... encounters a numeric overflow, it will fail; you haven't checked for that.
I don't believe that using scanf will solve this problem. scanf has undefined behavior if it reads a number outside the range of the specified type; storing a garbage value is a likely outcome. I can only guess that you're happen to be entering a smaller number with the scanf version of your program than with the cin >> ... version, and didn't notice that you were doing so.
You can use somewhat larger values (at the cost of not being able to store negative values) by using type unsigned long long, which has a minimum value of 0 and a maximum of at least 264-1, or 18,446,744,073,709,551,615, approximately 1.8 * 1019.
If you need even larger numbers, you might consider using floating-point, which gives you a much larger range at the expense of losing precision for large values.
Did you try to test small numbers such as 5, for example ? If it's working it's probably something in the number you enter which is probably out of the maximum that long long int can contain. Just try doing this on your system:
#include <iostream>
#include <stdio.h>
#include <limits>
using namespace std;
int main()
{
std::cout << std::numeric_limits<long long int>::max() << std::endl;
return 0;
}
and check if the value you entered is bigger than the one printed. If so, just declare a variable with enough space for the value, if the value printed is above the value you entered and there's STILL an error, comment on this post.
I have also encountered this problem, and you can get an ac by scanf and get an error by cin because of the example is special. In fact, if there is an overflowing, using these two input methods will also be wrong.
For long long type, for question I encountered at "A+B and C (64bit)", if we use the example data "9223372036854775808 -9223372036854775808 0" to A B C, we can get the error answer by the cin and get the correct answer by scanf;However, if we use the example data "9223372036854775808 -9223372036854775808 -1" to A B C, we can get the correct answer by cin and get the error answer by scanf.
So we should use another method to solve the problem.(or the input data is in ( 2-63, 263 ), and the input data will be legal.)
I'm trying to convert the string to int with stringstream, the code down below works, but if i use a number more then 1234567890, like 12345678901 then it return 0 back ...i dont know how to fix that, please help me out
std:: string number= "1234567890";
int Result;//number which will contain the result
std::stringstream convert(number.c_str()); // stringstream used for the conversion initialized with the contents of Text
if ( !(convert >> Result) )//give the value to Result using the characters in the string
Result = 0;
printf ("%d\n", Result);
the maximum number an int can contain is slightly more than 2 billion. (assuming ubiquitios 32 bit ints)
It just doesn't fit in an int!
The largest unsigned int (on a 32-bit platform) is 2^32 (4294967296), and your input is larger than that, so it's giving up. I'm guessing you can get an error code from it somehow. Maybe check failbit or badbit?
int Result;
std::stringstream convert(number.c_str());
convert >> Result;
if(convert.fail()) {
std::cout << "Bad things happened";
}
If you're on a 32-bit or LP64 64-bit system then int is 32-bit so the largest number you can store is approximately 2 billion. Try using a long or long long instead, and change "%d" to "%ld" or "%lld" appropriately.
The (usual) maximum value for a signed int is 2.147.483.647 as it is (usually) a 32bit integer, so it fails for numbers which are bigger.
if you replace int Result; by long Result; it should be working for even bigger numbers, but there is still a limit. You can extend that limit by factor 2 by using unsigned integer types, but only if you don't need negative numbers.
Hm, lots of disinformation in the existing four or five answers.
An int is minimum 16 bits, and with common desktop system compilers it’s usually 32 bits (in all Windows version) or 64 bits. With 32 bits it has maximum 232 distinct values, which, setting K=210 = 1024, is 4·K3, i.e. roughly 4 billion. Your nearest calculator or Python prompt can tell you the exact value.
A long is minimum 32 bits, but that doesn’t help you for the current problem, because in all extant Windows variants, including 64-bit Windows, long is 32 bits…
So, for better range than int, use long long. It’s minimum 64 bits, and in practice, as of 2012 it’s 64 bits with all compilers. Or, just use a double, which, although not an integer type, with the most common implementation (IEEE 754 64-bit) can represent integer values exactly with, as I recall, about 51 or 52 bits – look it up if you want exact number of bits.
Anyway, remember to check the stream for conversion failure, which you can do by s.fail() or simply !s (which is equivalent to fail(), more precisely, the stream’s explicit conversion to bool returns !fail()).
This is a very basic question.Please don't mind but I need to ask this. Adding two integers
int main()
{
cout<<"Enter a string: ";
int a,b,c;
cout<<"Enter a";
cin>>a;
cout<<"\nEnter b";
cin>>b;
cout<<a<<"\n"<<b<<"\n";
c= a + b;
cout <<"\n"<<c ;
return 0;
}
If I give a = 2147483648 then
b automatically takes a value of 4046724. Note that cin will not be prompted
and the result c is 7433860
If int is 2^32 and if the first bit is MSB then it becomes 2^31
c= 2^31+2^31
c=2^(31+31)
is this correct?
So how to implement c= a+b for a= 2147483648 and b= 2147483648 and should c be an integer or a double integer?
When you perform any sort of input operation, you must always include an error check! For the stream operator, this could look like this:
int n;
if (!(std::cin >> n)) { std::cerr << "Error!\n"; std::exit(-1); }
// ... rest of program
If you do this, you'll see that your initial extraction of a already fails, so whatever values are read afterwards are not well defined.
The reason the extraction fails is that the literal token "2147483648" does not represent a value of type int on your platform (it is too large), no different from, say, "1z" or "Hello".
The real danger in programming is to assume silently that an input operation succeeds when often it doesn't. Fail as early and as noisily as possible.
The int type is signed and therefor it's maximum value is 2^31-1 = 2147483648 - 1 = 2147483647
Even if you used unsigned integer it's maximum value is 2^32 -1 = a + b - 1 for the values of a and b you give.
For the arithmetics you are doing, you should better use "long long", which has maximum value of 2^63-1 and is signed or "unsigned long long" which has a maximum value of 2^64-1 but is unsigned.
c= 2^31+2^31
c=2^(31+31)
is this correct?
No, but you're right that the result takes more than 31 bits. In this case the result takes 32 bits (whereas 2^(31+31) would take 62 bits). You're confusing multiplication with addition: 2^31 * 2^31 = 2^(31+31).
Anyway, the basic problem you're asking about dealing with is called overflow. There are a few options. You can detect it and report it as an error, detect it and redo the calculation in such a way as to get the answer, or just use data types that allow you to do the calculation correctly no matter what the input types are.
Signed overflow in C and C++ is technically undefined behavior, so detection consists of figuring out what input values will cause it (because if you do the operation and then look at the result to see if overflow occurred, you may have already triggered undefined behavior and you can't count on anything). Here's a question that goes into some detail on the issue: Detecting signed overflow in C/C++
Alternatively, you can just perform the operation using a data type that won't overflow for any of the input values. For example, if the inputs are ints then the correct result for any pair of ints can be stored in a wider type such as (depending on your implementation) long or long long.
int a, b;
...
long c = (long)a + (long)b;
If int is 32 bits then it can hold any value in the range [-2^31, 2^31-1]. So the smallest value obtainable would be -2^31 + -2^31 which is -2^32. And the largest value obtainable is 2^31 - 1 + 2^31 - 1 which is 2^32 - 2. So you need a type that can hold these values and every value in between. A single extra bit would be sufficient to hold any possible result of addition (a 33-bit integer would hold any integer from [-2^32,2^32-1]).
Or, since double can probably represent every integer you need (a 64-bit IEEE 754 floating point data type can represent integers up to 53 bits exactly) you could do the addition using doubles as well (though adding doubles may be slower than adding longs).
If you have a library that offers arbitrary precision arithmetic you could use that as well.