3

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

5 Answers 5

6
   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)
^^^^^^^^^^^
Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

try declaring it string ans(...)
3

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
}

Comments

2

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

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

  string s = "Lol";

  return s; 
}

Comments

0

you have also to avoid using global variables :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.