Display the middle char in an string please help

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 if 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;
}
1. Divide count by 2 and save this number.
2. If you detect an odd number of characters, get the character at the result - 1 of the first step.
3. Else get the two characters at the result - 1 of the first step.
In case you haven't already finished the coding, here's what I came up with.
Thanks for asking about this, as I was then able to learn how to do it as well.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Middle Char.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
char line [80];
char* ptr1 = line;
int count = 0;

cout << "Enter a string of characters." << endl<< " (Max length allowed is 80 )" << endl;
cin.getline(line, 80);

cout << endl << endl;
cout << "The string you entered was :" << endl << endl << ptr1  << endl;

while ( *ptr1 != '\0' )
	{
		++count;
		++ptr1;
	}
cout << endl << "Your string consists of " << count << " characters." << endl << endl;
if (count % 2 == 0)
	{
		cout << "The string has an even number of characters," << endl;
		cout << "so the middle two characters are : < '" << line[count/2-1] << line[count/2] << "' >." << endl << endl ;
	}
else 
	{
		cout << "The String has an odd number of characters," << endl;
		cout << "so the middle character is : < '" << line[count/2] << "' >." << endl << endl ;
	}
cout  << "\t\t";
return 0;
} 


Last edited on
closed account (zb0S216C)
I can see an issue with your code, Nelli. line is uninitialized. Each character of line contains unused memory. When you ask for input, the given characters are stored into the corresponding slot within line. However, when the user enters less than 80 characters, the remaining characters still remain uninitialized. In such an event, you would have to scan each character within the array to see if it's valid.

[I see many users who create uninitialized variables. It's like they've never heard of a constructor.]

Wazzak
Topic archived. No new replies allowed.