Welcome to HBH! If you have tried to register and didn't get a verification email, please using the following link to resend the verification email.

C++ functions


ghost's Avatar
0 0

im having and issue with with a function

#include <cstdlib>
#include <iostream>
#include <string>
//When i do int it is bolded in my complier and "string" is not i do have 
//the include string but nothing seems to be working.
//the errors sayes " 'string' undecleared "
string Username()    
{
       return "Bob";
       }
using namespace std;

int main(int argc, char *argv[])
{
    cout << Username() << endl;
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

ty for your time

zer0pain


ghost's Avatar
0 0

Well, sorry I don't really understand what you mean but if you don't even include the int, let's say before string it works fine if you want the ouput as "bob".

#include <cstdlib> #include <iostream> #include <string> string Username() { return "Bob"; } using namespace std;

int main(int argc, char *argv[]) { cout << Username() << endl;

system("PAUSE"); return EXIT_SUCCESS; }


ghost's Avatar
0 0

Well duh! :p You try and use an std::string before you declare "using namespace std;" so either modify your code so it looks like this..

#include &lt;cstdlib&gt;
#include &lt;iostream&gt;
#include &lt;string&gt;

std::string Username()
{
return &quot;Bob&quot;;
}

int main(int argc, char *argv[])
{
std::cout &lt;&lt; Username() &lt;&lt; std::endl;

system(&quot;PAUSE&quot;);
return EXIT_SUCCESS;
}

or just move the "using namespace std;" above your function definition like so..

#include &lt;cstdlib&gt;
#include &lt;iostream&gt;
#include &lt;string&gt;

using namespace std;

string Username()
{
return &quot;Bob&quot;;
}

int main(int argc, char *argv[])
{
std::cout &lt;&lt; Username() &lt;&lt; std::endl;

system(&quot;PAUSE&quot;);
return EXIT_SUCCESS;
}

ghost's Avatar
0 0

what does themarkupusing namespace std;do i havent gotten that far and my complier puts in in there and the book i have uses a differnt complier!

ty 4 u time zer0pain


ghost's Avatar
0 0

The "using namespace std" simply tells the compiler to use the names defined in the standard library as if they were functions that you defined in your program yourself pretty much. I suggest you continue to read further along in the book because they are bound to explain it sooner or later, and as a side-note, "using namespace std" isn't considered a good programming habit and should not be used unless you are really really lazy. :p;)