由于程序执行了正确次数的循环,我们知道除法在起作用,但是我似乎无法获得字符串变量“result”中的任何内容的输出。有帮助吗?
#include <iostream>
#include <string>
using namespace std;
int main ()
{
int base,decimal,remainder;
string result;
cout <<"Welcome to the Base Converter. Please enter in the requested base from 2-16"<<endl;
cout <<"and an integer greater than or equal to zero and this will convert to the new base."<<endl
do
{
cout <<"Please enter the requested base from 2-16:"<<endl;
cin >>base;
}while (base<2 || base>16);
do
{
cout <<"Please enter the requested integer to convert from base 10:"<<endl;
cin >>decimal;
}while (decimal<0);
do
{
decimal=decimal/base;
remainder=decimal%base;
if (remainder<=9)
{
string remainder;
result=remainder+result;
}
else
{
switch(remainder)
{
case 10:
{
result="A"+result;
}
我的开关还有一些情况,但我相信问题出在我的变量声明或我的字符串类中。有什么明显的解决方案吗?
最佳答案
您发布的代码不完整,如果没有看到函数的其余部分,我无法确定这是否是正确的解决方案。但是,您修改 result
的方式您发布的代码段中的变量显然不正确。
当你在给定上下文中声明一个与另一个变量同名的局部变量时,它会隐藏之前声明的变量。所以如果你写
int remainder = 0;
std::string result = "";
if (remainder<=9)
{
std::string remainder; //this hides the outer-scope remainder variable for this code block
result=remainder+result;
}
就跟你写的一样
result = "" + result;
这显然是空操作。
在 remainder
前面加上一个字符串的值你应该这样做:
if (remainder<=9)
{
std::string remainder_str = std::to_string(remainder); //note different name and initialization value
result = remainder_str + result;
}
或者只是
result = std::to_string(remainder) + result;
请注意to_string自 C++11 起在 header <string>
中可用.如果你不能使用 C+11,你可以使用 itoa相反。
关于c++ - 我的程序执行了正确的循环 # 次,但我看不到字符串变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39864798/