-6

so I'm kinda new to c++ (actually very new) and I was messing around with my code:

#include <iostream>

using namespace std;

string aString()
{
    cout << "Car" << endl;
}

int main()
{
    cout << "Word:" << aString() << endl;
    return 0;
}

I tried to get something like: "Word: Car".

It ended up not working and showing a bunch of weird characters. My question is can a function return a string like an integer does?

Sorry if this is a stupid question.

Mike W
  • 31
  • 1
  • 1
  • 3
  • `using namespace std;` is not a good idea - please google it – Ed Heal Jul 10 '16 at 12:49
  • 6
    It certainly can. Except that you're not returning a string. Your compiler should've issued a warning, which you probably ignored. Do not ignore warning messages from your compiler. The compiler does not issue warning messages just because it feels like it. – Sam Varshavchik Jul 10 '16 at 12:50
  • You forgot to `#include ` The code is not guaranteed to compile. – PaulMcKenzie Jul 10 '16 at 13:04

1 Answers1

10

My question is can a function return a string like an integer does?

Sure, you want to write

string aString()
{
    return "Car";
 // ^^^^^^
}

If the function declares a return type, you actually need to return something, otherwise you have undefined behavior.

The compiler should have issued a warning about that.

std::cout is used to print out values at the terminal, not to return them from functions.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Thanks! It worked. I'm trying to learn c++, do you know any good sites? I have almost no experience with programming languages (only a bit c#, html, js) – Mike W Jul 10 '16 at 12:51
  • 2
    @MikeWu Have a look [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – πάντα ῥεῖ Jul 10 '16 at 12:55