...,but they only work if the numbers are in the first position.
Example SS:
string placa= 778ASD
n would be<<778
but if string placa=ASD778
n would be=0
Example STOI:
string placa=778ASD
n would be<<778
but if string placa=ASD778
n would be<<terminate called after throwing an instance of 'std::invalid_argument'
what(): stoi
Can you help me to understand why isn't it working? Thanks!
It's because
1. stoi won't convert letters to integers. It just doesn't work (as far as I know).
2. Letters in stringstream won't convert to integers like that.
What you need to do is use a for loop and iterate through the string, probably use isalpha() or isdigit() to figure out if each individual element is a character or an integer.
#include <iostream> // good idea to include this first
#include <string>
#include <cstring> // needed to use c-string functions
#include <cctype> // needed to use isalpha() and isdigit()
int main ()
{
int integer {};
std::string placa {};
char cplaca[256] {'\0'};
char nums[10] {'\0'};
std::cout << "Enter placa. \n: ";
std::cin >> placa;
strcpy (cplaca, placa.c_str() ); // convert std::string to c-string
int counter {0};
for (unsigned i = 0; i < placa.size(); ++i) // This is the main thing; just iterates through the c-string
{ // and puts any numbers it finds into the c-string nums[]
if (isdigit ( placa.at(i) ) )
{
nums[counter] = cplaca[i];
}
else
{
continue;
}
++counter;
}
integer = atoi (nums); // use atoi() to convert nums[] to int
std::cout << integer << std::endl;
return 0;
}
I know that's not the neatest way to do it, but I was trying to explain it a bit more.
Hope that helps!
max
Thanks to both of you, I was able to complete my task with what you said and learnt something I think is gonna be really useful!
PD: Agent Max, I know it's just a way to write it, but why do you add"{}" after declaring the varibles? Is it only a stetical thing or does it do something? I just started programming a month ago and had never seen that. Ty!
{} isn't needed for a class with a default constructor. Also for char, the default is 0 so {'\0'} can be just {}. The default for int is 0 and for double 0.0 so int{0} is just int{}.