私はcharをintに変換する小さなプログラムを書いています。プログラムは、フォーム'1234'
の文字を読み込み、その後、出力INT 1234
:手作業でcharをintに変換する - 奇妙な振る舞い
#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;
}
これは小さな文字で正常に動作しますが、私は12345678901
のように大きな文字(上記の長さ11とを)しようとすると、プログラムが間違っを返します結果、-539222987
。
何が起こっているのですか?
整数オーバーフロー? – Laurel
システム上の 'int'のサイズはどれくらいですか?' int'が保持できるシステム上の最大値は何ですか? –
ヒント:intに格納できる最大の数字は何ですか? – alex