After having studied some library functions cctype
like isdigit
e, isalpha
I decided to create a program, inspired by some tutorials I saw on yt, to validate integers.
Below my code:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool tipo_i_valido(string s);
int capturar_i();
int main()
{
int numero;
numero = capturar_i();
cout << "El numero ingresado es: " << numero << "\n" << endl;
return 0;
}
bool tipo_i_valido(string s)
{
int i, longitud_s;
longitud_s = s.length();
if (longitud_s == 1)
{
if (!isdigit(s[0]))
return 0;
}
else
{
if (s[0] == '+' || s[0] == '-' || isdigit(s[0]) != 0)
{
for (i = 1; i < longitud_s; i++)
{
if (!isdigit(s[i]))
return 0;
}
}
else
return 0;
}
return 1;
}
int capturar_i()
{
int n_numero;
string numero;
bool es_valido;
do {
cout << "Ingrese un numero:\t";
getline(cin, numero);
cout << "\n";
es_valido = tipo_i_valido(numero);
if (!es_valido)
cout << "ERROR. Ingrese solo numeros enteros.\n" << endl;
} while (!es_valido);
n_numero = stoi(numero);
return n_numero;
}
As you can see, what I do is enter a string and if it turns out to be an integer including the sign, for example, +24
or -12
, then it considers it valid and the program converts the string using stoi
. My problem is that for some reason in VS 2017, when I run my program, if I put the character ñ
the program crashes and I get the following message: "debug assertion failed [...]". However, the code above, after compiling it to Dev C++ 5.11, runs as normal when executed.
Why is it that in VS the character ñ
crashes my program, but in Dev C++ it doesn't?
Thanks in advance for your responses and/or comments.
This is due to the behavior of functions
isXXX
, includingisdigit( )
, in combination with your system's character encoding.According to the standard :
In free translation on my part:
There you have the reason. Your system encodes the character
'ñ'
as a numeric value not representable in aunsigned char
(probably usewchar_t
for characters).In these cases, the compiler is free to salvage the situation as best it can ; VS2017 shows you the message, while the compiler included in Dev C++ 5.11 sure uses another type for characters, and is capable of dealing with non-ASCII characters.
In any case, both compilers are correct. That's what undefined behaviors have ;-)