is a string of characters odd or even?

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.


#include <iostream>
#include <iomanip>
#include "stdafx.h"

using namespace std;

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 " << count << " characters" << endl;


system ("Pause");
return 0;
}
Look into strlen() to find the length of the string, then simply use the modulus operator to check if it's even or odd.
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?
Modulus returns the remainder of the division operation. If you remember your gradeschool math, think about remainder:

http://www.icoachmath.com/math_dictionary/remainder.html

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?

#include <iostream>
#include <iomanip>
#include "stdafx.h"

using namespace std;

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;

system ("Pause");
return 0;
}
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.
Last edited on
Topic archived. No new replies allowed.