I have some simple code that reuest a user to input a string of characters (up to a length of 81)
I need to discover if the ctring had an even or odd number of charcters and then display the middle characters (middle two if the string is odd). Please look at the code and advise me on how to proceed.
Thanks so much for the tip and I understand (after reading) how to utilize the strlen() to output the total number of characters, but can you please be a lil more specific on how to utilize the modulus to check for odd or even and diplay the middle character?
In this way you can check if an operation is odd or even by checking the result of a variable % 2 operation. (HINT : if something is divisible by something else, would it have a remainder?)
Ok this is what I got and the results determine if the string is odd or even but I need to display the middle character if even and the middle two id odd
how do I get that?
int main()
{
char line [80];
char* ptr1 = line;
int count = 0;
cout << "Enter a string of charcters. Max length allowed is 80 " << endl;
cin.getline(line, 80);
cout << endl << endl;
cout << "The string you enter was " << endl << line << endl;
while ( *ptr1 != '\0' )
{
++count;
++ptr1;
}
cout << "Your string consisted of " << strlen(line) << " characters" << endl;
if (count % 2 == 0)
{
cout << "The string had an even number of characters" << endl;
}
else cout << "The String had an odd number of characters" << endl;
We can't give you the answer to everything. But if I were you, I'd use an IF statement to determine the course of action based on whether or not it's odd. If it is, just get the character at position str[((len / 2) + 1)], otherwise, well... you'll have to figure that out yourself.