LoneDruidOfTheDarkArts
LoneDruidOfTheDarkArts

Reputation: 385

Questions about string and functions.

I am playing around some in C++, just for fun. I have just begun to use functions, and I want to make an if-statement that goes to different functions based upon if the user is trying to multiply by 1 or not.

Here is the code:

//Test för att se om jag förstår funktioner

#include <iostream>
#include <string>

using namespace std; 

//Deklarerar variblar som jag ska använda
int a,b,x;
string s;

//Skriver ut funktionen för att multiplicera
int multi(int a, int b) 
{
  x = a * b; 

  return x;
}

int ans(void)  
{
  using std::string; 

  string s = "Lol";

  return s; 
}

//Samlar in värde från användaren, skickar den till funtktionen "multi" som multiplicerar den, sedan skickar den tillbaks den till main via return. Main visar sedan
//resultatet för användaren

int main( void ) 
{

  using std::cout;
  using std::cin;
  using std::string; 

  cout << "Ange ett nummber som du vill multiplicera: \n\n"; 
  cin >> a;
  cout << "\n";
  cout << "Ange det andra nu: \n"; 
  cin >> b; 
  cout << "\n";


 if(a == 1) 
 {
  multi(a,b); 

  cout << "Svaret är: " << x << "\n";
 }
 else
 {
   ans;
   cout << s;
 }

  return 0; 

}

The only thing that happens is that it returns the message;

adrian@adrian-HP-ProBook-4525s:~/Documents/code$ g++ test10.cpp -o test test10.cpp: In function ‘int ans()’: test10.cpp:26:10: error: cannot convert ‘std::string {aka std::basic_string}’ to ‘int’ in return

It is so weird because from all I can see I am not trying to convert it back, am I?

//Regards

Upvotes: 3

Views: 216

Answers (5)

Hicham
Hicham

Reputation: 979

you have also to avoid using global variables :

//Deklarerar variblar som jag ska använda
int a,b,x;
string s;

Upvotes: 0

Furqan
Furqan

Reputation: 268

You are returning a string whereas return type of function is Integer

int ans(void)  
{
  using std::string; 

  string s = "Lol";

  return s; 
}

Upvotes: 2

K-ballo
K-ballo

Reputation: 81409

Here is the problem:

int ans(void) // The function is declared to return int
{
  using std::string; 

  string s = "Lol";

  return s; // It tries to return s, which is a string
}

Upvotes: 3

Alok Save
Alok Save

Reputation: 206646

   int ans(void)  
   ^^^^^

You are trying to return s which is std::string in the function body, but your function signature says function is returning an int. So, the compiler tries to convert the std::string to int which is an invalid conversion and hence the error.

It should be:

std::string ans(void)
^^^^^^^^^^^

Upvotes: 6

leo
leo

Reputation: 1117

int ans(...) is returning s, which is a string

Upvotes: 3

Related Questions