我一直在阅读C ++ Primer Plus,第8章的第一个练习要求我通过地址将字符串传递给函数然后打印字符串。然后另一个函数打印字符串的次数等于调用函数的次数,除非第二个参数(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 :(得分: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;
}
答案 1 :(得分:0)
取消引用字符串并使用#include <string>
时已经explained by Blake了,如果我理解正确的话,练习是关于使用单个函数,而不是两个函数。我认为,他们的意思是这些(code on ideone.com):
#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!