Mar 13, 2012 at 5:59am UTC
I'm working a problem that returns a string containing the character in str if the length of str is odd, or the two middle char if the length is even.
here is what i got, and i just dont no how to call for the function. help!
#include <iostream>
#include <string>
using namespace std;
string middle(string str)
{
int i = str.length();
if (((i = str.length() / 2) % 2) == 0)
{
cout << str[i - 1];
}
if (((i = str.length() / 2) % 2) >= 1)
{
cout << str[i];
}
return str;
}
int main()
{
string input;
cout << "Enter a word to print the middle character: ";
cin >> input;
int i = input.length();
string result = middle(i);
cout << "The middle char is: " << i << endl;
system ("pause");
return 0;
}
Mar 13, 2012 at 4:42pm UTC
Thanks for your help stewbond, i have change the function a little bit but it still would not work. Please let me know where i did wrong.
if ( i % 2 == 1)
{
cout << str.substr((i/2), 2);
}
if (i % 2 == 0)
{
cout << str.substr((i/2), 1);
}
return str;
}
Mar 13, 2012 at 6:11pm UTC
Do not call main() in C++ code.
It is forbidden by the C++ standard, though some compilers will allow you to do it.
In addition, it can lead to dangerous recursion/memory leaks.
Use a while loop or something similar if you want to be able to enter additional words.
Mar 13, 2012 at 7:40pm UTC
I added main() in because I did not wonted to run program again if I wonted to test another string. And left it in.
Mar 13, 2012 at 9:06pm UTC
You can write your function
middle without using if-statement.:)
1 2 3 4 5 6
std::string middle( const std::string &s )
{
std::string::size_type j, i = ( j = s.size() / 2 ) % 2 == 0;
return ( s.substr( j - i, i + 1 ) );
}
Sorry, I am wrong. It is invalid code. The correct code will look
1 2 3 4 5 6 7 8 9 10
std::string middle( const std::string &s )
{
std::string::size_type i, j;
j = s.length();
i = j % 2 == 0;
j /= 2;
return ( s.substr( j - i, i + 1 ) );
}
Last edited on Mar 13, 2012 at 9:15pm UTC
Mar 14, 2012 at 8:21am UTC
Thanks everyone for the help, i got it!!