Open Courseware CS106b の課題 1 を試していました。問題 4 に行き詰まりました。この問題では、再帰を使用して整数を文字列コンバーターに書き込む必要があります。整数変換を実行するライブラリ関数は使用できません。
問題は、すべての「再帰レベル」の後、コードが前の文字列を追跡しないため、文字列に追加してビルドできないことです。
#include <iostream>
#include <string>
#include "console.h"
#include "simpio.h"
using namespace std;
/* Function prototypes */
string intToString(int n);
int stringToInt(string str);
/* Main program */
int main() {
// [TODO: fill in the code]
int n = getInteger("Enter number for conversion to String: ");
cout<< "Converted to String: "<<intToString(n);
return 0;
}
//Functions
string intToString(int n){
double toBeDecomposed = n;
string convertedToString;
char ch;
string tempString;
if((double)(toBeDecomposed/10) >= 0.1){
int lastDigit = (int)toBeDecomposed%10;
toBeDecomposed = (int)(toBeDecomposed/10);
intToString(toBeDecomposed);
if (lastDigit == 0) {
ch = '0';
}
else if (lastDigit == 1) {
ch = '1';
}
else if (lastDigit == 2) {
ch = '2';
}
else if (lastDigit == 3) {
ch = '3';
}
else if (lastDigit == 4) {
ch = '4';
}
else if (lastDigit == 5) {
ch = '5';
}
else if (lastDigit == 6) {
ch = '6';
}
else if (lastDigit == 7) {
ch = '7';
}
else if (lastDigit == 8) {
ch = '8';
}
else if (lastDigit == 9) {
ch = '9';
}
tempString = string() + ch;
convertedToString = convertedToString.append(tempString);
cout<<convertedToString<<endl;
}
cout<<"Returning: "<<convertedToString<<endl;
return convertedToString;
}
int stringToInt(string str){
return 0;
}
私のデバッグ出力は、最後の桁のみを返すことを示しています:
ConvertedToString
変換された整数全体を返すように、文字列に正常に追加する方法を誰かが提案できますか?