Basically I feel like I've almost got it figured out. But for some reason I always get "expected primary-expression before "else"" and "expected ';' before "else"" I really don't understand why it doesn't work and I feel like my logic works. Maybe it doesn't? Could really use an explanation here! **Please note orginally I had the program set up to tell me whether the string had an odd or even number of characters so in the main there are some things that shouldn't be there but now I'm mostly concerned with the function.
#include <iostream>
#include <string>
using namespace std;
string even(string str)
{
string o;
string e;
int d;
int i = str.length(); //# of digits per string.
if ((i % 2) == 0)
{
int d = i/2;
e = str.substr(d,(d + 1));
}
return e; //This is even.
else
{
int d = i/2;
o = str.substr (d);
}
return o; // This is odd.
}
int main()
{
string input;
string x;
string y;
cout << "Please enter a number to see if its even or odd: ";
cin >> input;
cout << even(input) << endl;
system ("pause");
return 0;
}
hey thanks that worked! it compiled but when I enter in a word it doesn't output like I want it too. for example i enter in haggle and it outputs "gle" or dog and i get "og" what am I doing wrong? ideally the output should be "gg" for haggle and "o" for dog
So, you want a function named 'even' to return a substring that consists of the center-most character(s) of the supplied string after asking the user to "enter a number to see if it's even or odd?"
Note that string::substr takes two arguments. The second one is the length of the string to extract. If you don't supply the second argument, it is assumed that you want the substring from the position indicated to the end of the string.