Your if (convert == s1.length())
is very strange. That expression is comparing an uninitialized char
variable to the length of the s1
string (which will be of size_t
type). What you should be doing is comparing the i
variable to the length (and that i
would be better defined as size_t
type).
Also the static_cast <int> (convert);
line does nothing. You can't change the type of a variable like that; instead, you should use the cast on the operand of the cout <<
in the following line. And note that, when casting a character digit to its integer value, you need to subtract the value of '0'
from it.
Here's a fixed version that addresses the above issues:
#include <iostream>
#include <string> // You 'forgot' this required header
size_t i = 0; // The "size_t" type is better suited for container sizes and lengths
void parseToInteger(std::string s1)
{
char convert;
// std::string another; // Never used!
if (i == s1.length()) { // Here, we've reached the end of the string
std::cout << std::endl; // prints nothing
}
else {
convert = s1.at(i++);
std::cout << cout << static_cast <int> (convert - '0'); // Apply the cast here
parseToInteger(s1);
}
}
int main()
{
std::string s0;
std::cout << "Enter a string to convert it into its integer value: ";
std::getline(std::cin, s0);
parseToInteger(s0);
return 0;
}
But note, there are other concerns in your code, as mentioned in the comments. First, it would be better to pass the s1
argument by reference; second: Are global variables bad?
Here's a version of your function that addresses these last two concerns:
void parseToInteger(std::string& s1, size_t i = 0)
{
if (i == s1.length()) { // Here, we've reached the end of the string
std::cout << std::endl; // 'flushes' output stream
}
else {
char convert = s1.at(i++);
std::cout << static_cast <int> (convert - '0'); // Convert to int
parseToInteger(s1, i);
}
}
The default value (of zero) for the new i
argument means that you don't have to change the call in the main
function.