我遇到了麻烦的一个例子,我正在编译从我的C++全合一为哑剧,第二版。它应该做的是显示包含CR(命名者)NQ的10行代码;然而,每次运行时,我都会得到10个变量地址。我试着在网上搜索这个问题,但它很特别。我正在运行Linux openSUSE 12.1并使用代码::Block (GCC)。我开始认为,包含的附加函数可能存在库问题。要么就是我完全失明了,这很明显。
#include <iostream>
#include <sstream>
#include <cstdlib>
using namespace std;
string *getSecertCode()
{
string *code = new string;
code->append("CR");
int randomNumber = rand();
ostringstream converter;
converter << randomNumber;
code->append(converter.str());
code->append("NQ");
return code;
}
int main()
{
string *newcode;
int index;
for (index =0; index < 10; index++)
{
newcode = getSecertCode();
cout << newcode << endl;
}
return 0;
}发布于 2011-12-06 21:12:36
问题似乎是
cout << newcode << endl;因为"newcode“是字符串*而不是字符串。
试一试
cout << *newcode << endl;而不是。
正如您所说的,您是初学者:不要忘记,删除,您正在分配的内存(new!)。
发布于 2011-12-06 21:20:07
尽可能避免使用指针。你不需要他们在这里。
string getSecertCode()
{
string code;
code.append("CR");
[...]
code.append(converter.str());
code.append("NQ");
return code;
}
int main()
{
string newcode;
[...]
}发布于 2011-12-06 21:13:29
问题是你把一个指针插入到cout中。
变化
cout << newcode << endl;至
cout << *newcode << endl;你会看到你的价值观。
对于指针,如果您想查看指针的值,就必须取消引用,如下所示
*pointer;如果您希望查看该值的地址,只需使用指针。
https://stackoverflow.com/questions/8406883
复制相似问题