Conversion problem

Why when it converts number to string it appears a large negative number?
I want my number to be less than 14 characters.


for example I enter 1234567899988888887654321 and appears an -886285364263


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include "stdafx.h"
#include <string>
#include <conio.h>
#include <iostream>
#include <sstream>
using namespace std;

//Funcion para el Output
void output(string x, string y)
{
	

	cout << " You enter: " << x.substr(0, 14) << "  " << y.substr(0, 14) << endl;



}

int main()
{
	//Variables
    int number;
	string name;
	stringstream ss;
	

	cout << " Please enter a your name\n\n";
	getline(cin, name);
	cout<<"\n\n " << name.substr(0, 14)<<"\n\n";

	cout << " Enter a number\n\n";
	cin >> number;
	ss << number;
	string newstring = ss.str();
	cout << "\n\n " << newstring.substr(0, 14) << "\n\n";


	if (number==0)
	{
		cout << "\n\n";
		
		return 0;
	}

	else
	{


		output(name, newstring);

	}


	system("Pause");
    return 0;
}
You do read a number into int. There is a limit, how large value an int can hold.
See http://www.cplusplus.com/reference/limits/numeric_limits/
> I enter 1234567899988888887654321 and appears an -886285364263

C++11:
If the conversion function results in a positive value too large to fit in the type of v, the most positive representable value is stored in v - http://en.cppreference.com/w/cpp/locale/num_get/get


1
2
3
4
5
6
7
8
9
10
11
12
13
#include <limits>
#include <iostream>

int main()
{
    int number = 0 ;

    std::cout << " Enter a number\n\n";
	std::cin >> number; // enter a positive value, larger than the maximum value int can hold

    std::cout << number << ' ' << std::numeric_limits<int>::max()
              << std::boolalpha << "  input failed? " << std::cin.fail() << '\n' ;
}

http://coliru.stacked-crooked.com/a/42aabc0e20f22404

Perhaps you are using the Microsoft implementation (which is still in C++98 mode wrt this)
In C++98/C++03, if an error occurs, v is left unchanged.
and what you are seeing is the (uninitialised) original value in 'number'
Topic archived. No new replies allowed.