所以我试着熟悉c++。下面是练习指针使用的任务。情况如下:
编写一个函数,提示用户输入他或她的名字和姓氏,作为两个单独的值。此函数应通过附加指针将两个值返回给调用方。只有当调用方传入姓氏的空指针时,它才会提示输入姓氏。
我试过几个版本。我现在被困的是:
#include <iostream>
#include <string>
using namespace std;
void getFullName(string *p_first, string *p_last) {
cout << "First name:";
getline(cin, *p_first);
if (!p_last) {
cout << "Last name:";
getline(cin, *p_last);
}
}
int main() {
string first;
string *p_first = &first;
string *p_last = NULL;
getFullName(p_first, p_last);
cout << *p_first << endl << *p_last << endl;
return 0;
}它坠毁了。我试图传递一个对“最后”的引用,然后指向它。但是在退出函数后,指针再次为NULL。
发布于 2013-01-20 15:25:16
我认为这项工作的案文有错误,应改为:
编写一个函数,提示用户输入他或她的名字和姓氏,作为两个单独的值。此函数应通过附加指针将两个值返回给调用方。只有当调用方传入姓氏的非空指针时,才会提示输入姓氏。
目前,您的代码通过取消引用空指针导致未定义的行为。
void getFullName(string *p_first, string *p_last) {
cout << "First name:";
getline(cin, *p_first);
if (!p_last) { /* <-- This test should be inverted */
cout << "Last name:";
/* Now, you get here only when p_last == NULL. On the next line,
* you dereference that null-pointer and try to read a string into
* non-existing memory: recipe for disaster.
* With the condition inverted, you would only get here if you have
* a string to store the text in. */
getline(cin, *p_last);
}
}发布于 2013-01-20 14:43:09
不要使用指针,这不需要指针。只需通过引用传递参数:
void getFullName(string& p_first, string& p_last) 但是,问题是您正在取消引用p_last,即NULL ->未定义的行为:
if (!p_last) { //this evaluates to true, because p_last==NULL
cout << "Last name:";
getline(cin, *p_last);
}发布于 2013-01-20 14:50:47
考虑到您的问题说明您使用了附加项,我会将其写为:
string getFullName()
{
string first, last;
cout << "First name:";
getline(cin, first);
cout << "Last name:";
getline(cin, last);
return first + last; // note use of additional
}https://stackoverflow.com/questions/14425591
复制相似问题