這是我的代碼(我只想使用字串作為引數):
#include <iostream>
using namespace std;
int i = 0; //to take string character by character
void parseToInteger (string s1)
{
char convert;
string another;
if (convert == s1.length()) //at null character function terminates
{
cout<<endl; // prints nothing
}
else
{
convert = s1.at(i );
static_cast <int> (convert);
cout<<convert;
parseToInteger (s1);
}
}
int main ()
{
string s0;
cout<<"Enter a string to convert it into its integer value: ";
getline (cin, s0);
parseToInteger (s0);
return 0;
}
這是我得到的錯誤:
Enter a string to convert it into its integer value: hello
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 32540) >= this->size() (which is 5)
有人可以幫幫我嗎?我正在學習編程。
uj5u.com熱心網友回復:
你if (convert == s1.length())的很奇怪。該運算式將未初始化 char的變數與字串的長度s1(將是size_t型別)進行比較。您應該做的是將i變數與長度進行比較(i最好將其定義為size_t型別)。
這static_cast <int> (convert);條線也不做任何事情。你不能像那樣改變變數的型別;相反,您應該cout <<在下一行的運算元上使用強制轉換。請注意,當將字符數字轉換為其整數值時,您需要從中減去 的值'0'。
這是解決上述問題的固定版本:
#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;
}
但請注意,如評論中所述,您的代碼中還有其他問題。首先,最好s1通過參考傳遞引數;第二:全域變數不好?
這是解決最后兩個問題的函式版本:
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);
}
}
新引數的默認值(零)i意味著您不必更改main函式中的呼叫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441488.html
上一篇:我可以在C 中添加可選型別引數嗎
