我必须定义一个接口(interface)。我作业中的API如下:
int generate_codes(char * ssn, char * student_id);
int 表示 0 或 1 表示通过或失败。 studentid 是一个输出参数,应该返回一个 6 位数字的 id。 ssn 是一个 9 位输入参数
他们的学校程序将使用 ssn 并使用我的代码生成学生 ID。
- 现在从 API 的角度来看,我不应该对两个参数都使用 const char *。
- 不应该通过引用传递 studentid 吗?而不是指针?
- 有人能告诉我如何轻松地在我的测试应用程序中使用指针,该应用程序使用我的 api 获取指针,以便它从 char * 打印 std::string 吗?
我的应用代码看起来像
const char * ssn = "987098765"
const char * studnt_id = new char [7];
int value = -1;
value = generate_codes(ssn,studnt_id);
std::string test(studnt_id);
std::cout<<"student id= "<<test<<" Pass/fail= "<<value<<std::endl;
delete [] studnt_id;
return 0;
我基本上得到了关于 << 与操作数右侧不兼容的错误。当我将代码更改为
std::cout<<"student id= "<<test.c_str()<<" Pass/fail= "<<value<<std::endl;
然后它起作用了,但我得到的值是垃圾。不确定如何从指针中获取值。函数内的值打印得很好。但是当我尝试在函数之外打印它时,它会打印垃圾。在上面的函数中,我确实像这样设置了 studndt_id
std::string str_studnt_id = studnt_id;
这是将一个字符串参数带到我执行代码生成的真实函数中。 当我准备好代码并想返回它时,我执行以下操作:
studnt_id = str_studnt_id.c_str();
是否应该使 str_studnt 的地址指向 studnt_id 的地址,因此我对其指向它的值所做的任何更改都应该反射(reflect)在函数外部?此 API 使用 char *,但我的函数使用 std::string。
最佳答案
这个错误看起来很奇怪。你确定它在正确的行中吗,因为它对我来说看起来不错。至于你的功能。至于你的问题:
从 C++ 的角度来看,您应该使用
const std::string &
作为输入参数,使用std::string &
作为输出参数。这看起来像这样:bool generate_codes(const std::string & ssn, std::string & student_id)
如果要表示通过或失败,返回值应该是
bool
。请参阅我对 1 的回答。
- 你从
const char *
构造一个std::string
看起来没问题,假设const char *
真的是 NULL-终止。
编辑 再次阅读您的问题后,我建议您考虑更改指针 和更改其指向的值 之间的区别.
关于c++ - 用于存储值的函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2556962/