#include <iostream>
#include <optional>
using namespace std;
void myFunction(optional<string> name = nullopt) {
if (name == nullopt) {
cout << "I wish I knew your name!" << endl;
}
else {
cout << "Hello " << name.value() << "!" << endl;
}
}
void getName(string Name){
cout << "input name: " << endl;
cin >> Name;
}
int main()
{
myFunction();
getName();
myFunction(Name);
return 0;
}
what would i do to make the getName function working ive tried a few things like adding a string as such string Name = getName()
but it wasnt working either.
CodePudding user response:
You could just create a function with a return value instead..
#include <iostream>
#include <optional>
#include <string>
using namespace std;
void myFunction(optional<string> name = nullopt) {
if (name == nullopt) {
cout << "I wish I knew your name!" << endl;
}
else {
cout << "Hello " << name.value() << "!" << endl;
}
}
string getName(){
string Name;
cout << "input name: " << endl;
cin >> Name;
return Name;
}
int main()
{
myFunction();
myFunction(getName());
return 0;
}
CodePudding user response:
You are not calling getName function with its defined parameter string name
. You should provide a string to your function while calling it getName("name");
CodePudding user response:
Obviously, Your code can not be compiled, because there's no definition of Name
in function main()
. Even if you fix it, it won't work properly. Because the Name
in function main()
and getName()
are not the same one. The Name
in function getName()
is just a copy of Name
in function main()
.
To fix it, try change the type of Name
in getName()
to string&
.
void getName(string& name) {
cout << "input name: " << endl;
cin >> name;
}
int main() {
string name;
getName(name);
}