Reverse c-string problem.

--Description of the problem--
Write a C++ program that will read up to 10 letters from the user and write the letters out in the reverse order. Use a period (".") to mark the end of the input, but you should not write that letter to the screen.
________________________________________________________________________________

--My questions--
-How do I remove the dot at the end of the input (see void removeDot)
-Is there some way I can write the getName function in a more efficient way?

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
40
41
42
#include <iostream>
#include <cstring>
using namespace std;

const char MAX_SIZE = 11;

void getName(char *name);
void reverseName(char *name);

int main()
{
    char name[MAX_SIZE];
    getName(name);
    cout << "The name is : " << name << endl;
    reverseName(name);
    cout << "The name reversed : " << name;

    return 0;
}
void getName(char *name)
{
    cin >> name;
    
}
void reverseName(char *name)
{
    char *start, *the_end, temp;

    start = name;
    the_end = name + strlen(name)-1;
    while(start < the_end)
    {
        // Swapping the letters.
        temp = *start;
        *start = *the_end;
        *the_end = temp;
        // The next letters we want to swap.
        start++;
        the_end--;
    }
}
Last edited on
read up to 10 letters

Your getName() doesn't do that.

Read letters (==characters) one by one until one of these becomes true:
* Read fails
* Letter is a dot
* Already have 10 letters
So this one get's accepted when I get a word with 10 or fewer char.
But it goes to hell when I write longer words

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <cstring>
using namespace std;

void readWord(char *word, int MAX_SIZE);
const int MAX_SIZE = 11;
int main() {

	char word [11];
	readWord(word, MAX_SIZE);

	cout << "The letters in reverse order:\n";
	for(int i = strlen(word)-1; i >= 0; i--)
    {
        cout << word[i];
    }
	return 0;
}

void readWord(char *word, int MAX_SIZE) {
	cout <<"Enter up to 10 letters followed by a period:" << endl;
	for(int i = 0; i < MAX_SIZE; ++i) {
		char currentChar;
		cin >> currentChar;
		word[i] = currentChar;
        if((currentChar == '.') || (currentChar == '\0'))
        {
            word[i] = '\0';
            return;
        }
	}
}

/*
// The old reverse name.
void reverseName(char *name)
{
    char *start, *the_end, temp;

    start = name;
    the_end = name + strlen(name)-1;
    while(start < the_end)
    {
        // Swapping the letters.
        temp = *start;
        *start = *the_end;
        *the_end = temp;
        // The next letters we want to swap.
        start++;
        the_end--;
    }
}
*/
Topic archived. No new replies allowed.