2016-10-05 1 views
1

プログラムはループを正しい時間実行するので、私たちは部門が動作していることを知っていますが、文字列変数 "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; 
      } 

私のスイッチにはいくつかのケースがありますが、問題は変数宣言または文字列クラスのどこかにあると思います。明らかな解決策はありますか?

+0

そして、一度に1行ずつコードを実行し、すべての変数を調べたときに、デバッガでどのような観測をしましたか? –

+1

'string remainder;'の目的は何ですか?私はあなたの整数の残りの同じ名前の残りの名前の文字列を宣言することを意味します。 – drescherjm

+0

C++にはまったく新しかったですが、デバッガでは何も普通のようには思えませんでしたが、すべてがきれいにコンパイルされました。 – Zach

答えて

1

投稿したコードが不完全で、これが残りの機能を見ずに正しい解決策であるかどうかはわかりません。ただし、投稿したスニペットの変数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のヘッダ<string>であるため利用可能であることに注意してください。 C + 11を使用できない場合は、代わりにitoaを使用できます。

+0

これで私のプログラムをコンパイルしようとすると、 "error: 'to_string'が 'std'のメンバーではありません。 result = std :: to_string(remainder)+ result; – Zach

+0

['to_string'](http://en.cppreference.com/w/cpp/string/basic_string/to_string)は、ヘッダ ''のC++ 11以降で使用できます。利用可能なものがあることを確認するか、[itoa](http:// www。cplusplus.com/reference/cstdlib/itoa/) – slawekwin

関連する問題