2016-05-12 4 views
0

私はC++ Primer Plusを読んできました。第8章の最初の演習では、文字列を出力する関数にアドレス経由で文字列を渡す必要があります。次に、別の関数は、2番目の引数(int型)が0に等しくない限り、関数が呼び出された回数に等しい回数だけ文字列を出力します。実際の文字列を出力する方法はわかりません。住所・アドレス。逆参照演算子を試しましたが、その結果エラーになります。文字列オブジェクトのアドレスを関数に渡す

/* Write a function that normally takes 1 argument, the address of a string, and prints that string once. 
    However, if a second, type int, argument is provided and is nonzero, the function should print the 
    string a number of times equal to the number of times that function has been called at that point. 
    (the number of times the function has been called is not equal to the int argument) 
*/ 
#include <iostream> 
#include <string.h> 
using namespace std; 

//global variables 
int times_called = 0; 

//function prototypes 
void print_str(const string * str); 
void print_str(const string * str, int i); 

int main() 
{ 
    string str = "Gotta catch'em all!"; 
    string * pstr = &str; 
    print_str(pstr); 
    print_str(pstr); 
    print_str(pstr, 1); 
    print_str(pstr, 0); 

    system("PAUSE"); 
} 

void print_str(const string * str) 
{ 
    cout << str; 
    cout << endl; 
} 

void print_str(const string * str, int i) 
{ 
    if (i != 0) 
    { 
     for (int count = 0; count <= times_called; count++) 
     { 
      cout << str; 
      cout << endl; 
     } 
    } 
    else 
    { 
     cout << str; 
     cout << endl; 
    } 
} 
+0

そしてまさにあなたの質問がある私は、彼らがこれらの行(code on ideone.com)に沿って何かを意味、と思いますか? – CoffeeandCode

+0

times_calledは常にゼロになっていますか? print_str(...、1)とprint_str(...、0)の間に違いはありません –

+0

その質問を含めるのを忘れました。文字列のアドレスではなく、文字列を出力する関数を取得するにはどうすればよいですか。 –

答えて

0

文字列を逆参照して#include <string>を使用すると、すでにexplained by Blakeでしたが、私が正しく理解している場合、運動は、単一の機能ではなく、2つの関数を使用してについてです。

#include <iostream> 
#include <string> 

void print_str(std::string const * _str, int _flag = 0){ 
static int count_call = 0; 
++count_call; 
int count_print = _flag ? count_call : 1; 

while(count_print--) 
    std::cout << *_str << std::endl; 
} 

int main(){ 
std::string str{"Hello, world!"}; 

print_str(&str); 
print_str(&str); 
print_str(&str); 
std::cout << std::endl; 

print_str(&str, 1); 
std::cout << std::endl; 

print_str(&str); 

return (0); 
} 

プログラムの出力:

Hello, world! 
Hello, world! 
Hello, world! 

Hello, world! 
Hello, world! 
Hello, world! 
Hello, world! 

Hello, world! 
+0

私はエクササイズにオーバーロードされた関数を使用していると解釈しましたが、これも機能します。ありがとうございました!ヘッダーファイルが間違っているような単純なものだとは信じられませんでした。 –

0

あなたの文字列を尊敬する必要があります。代わりに#include <string.h>#include <string>に変更する必要があります。

#include <iostream> 
#include <string> 

void print_str(const std::string* str) { 
    std::cout << *str << std::endl; 
} 

int main() { 
    std::string str = "Hello world!"; 
    print_str(&str); 
    return 0; 
} 

実行例: https://ideone.com/AGSk1k

+0

与えられたコードを使用すると、私の最後にはエラーが発生します。 エラーC2679:バイナリ '<<': 'const std :: string'型の右辺オペランドをとる演算子が見つかりません(または許容される変換はありません) –

+3

'#include 'は '#include '代わりに –

関連する問題