Trying to make a program which turns first and final letter of each words to uppercase

As the title says, that's the program.
Everything works fine until I enter more than one blank space.
E.g. they are tall - works fine ; they are tall - returns TheY ArE
Why does this happen?

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
  // siruri-de-caractere.cpp : Defines the entry point for the console application.
//

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

using namespace std;

int main()
{
	char s[999];
	cin.get(s, 999);
	cin.get();
	int n = strlen(s);
	s[0] -= 32;
	s[strlen(s) - 1] -= 32;
	for(int i = 0; i < n; i++)
	{
		if (s[i] == ' ')
		{
			s[i - 1] -= 32;
			s[i + 1] -= 32;
		}
	}
	cout << s;
    return 0;
}

You are subtracting 32 from all characters that are next to a space. Space has ASCII value 32, so when a space is next to another space it ends up as 0. A character with value 0 is a null character ('\0') and is used to mark the end of strings. This means that when you later try to print the string it stops where the two consecutive spaces were, thinking it's the end of the string.
Last edited on
Topic archived. No new replies allowed.