Search code examples
c++stringdefinitions

Why isn't my C++ program working?


No idea why this isn't working, everything seems to be right but maybe I'm missing something obvious as I'm just getting to know C++.

Program:

#include <iostream>
#include <string>
using namespace std;

string ask(){
    string ans2;
    cout << "Type:";
    cin >> ans2;
    return ans2;

}

int main()
{
    string ans2;
    string ans1="Hello";
    ask();
    cout << ans1 << " turns into " << ans2;
    return 0;
}

With the error message of:

Line 20:[Error] no match for call to '(std::string {aka     std::basic_string<char>}) (std::string&)'

Line 6:[Error] 'ans2' was not declared in this scope
Line 6:[Error] expected ',' or ';' before '{' token

Solution

  • The ans2 in main and in ask are two different variables. When you return the value of ans2 in your ask function, you need to capture it in your main function via ans2 = ask();. Working example on ideone