#include <iostream>
#include <cstring>
usingnamespace std;
void capMyString(char * ptr) // creates an function that caps the first letter of each sentence
{
int space = 0;
int period = 0;
for(int i =0; i < strlen(ptr); i++)
{
if(space == 1 && period == 1)
{
toupper(*ptr);
cout << toupper(*ptr);
}
else
{
if(period ==1)
{
if(*ptr = ' ')
{
space = 1;
}
else
{
period = 0;
}
}
else
{
if(*ptr = '.')
{
period = 1;
}
else
{
period =0;
}
}
}
}
}
int main()
{
constint SIZE = 100;
char text[SIZE];
cout << "Please enter a string of text: " << endl;
cin.getline(text,SIZE);
capMyString(text);
return 0;
}
So the problem is that it is printing out numbers (I did this so I could see where my errors were and that's why I have the cout right there). For example, if I type in "hello" it prints out "323232". Does anyone know why it is doing this? And if so, how can I make it to where it is not.
*ptr should be ptr[i] or *(ptr+i) everywhere, otherwise you'll only ever be looking at the first character.
Lines 21 and 32 need an extra = sign (comparison is ==; one = is assignment).
toupper(x) doesn't actually convert x to uppercase; it merely returns the uppercase version of x. So to actually convert x to uppercase, you need to do x = toupper(x);.
You never reset space and period to 0 after you turn a character to uppercase.
EDIT: And for the reason why it's printing out "32"s, *ptr ends up getting set to equal ' ' (space character), which is 32 in ASCII. Since toupper returns an int, it prints 32 out instead of ' '.
That code will certainly give you the correct output, but it'll mess up the original string in the process.
Try putting cout << '\n' << text; on line 71 to see what I mean.
To fix that, you'll have to change *ptr to *(ptr+i) (or ptr[i], which might be easier to read) on lines 22 and 23.
#include <iostream>
#include <cstring>
usingnamespace std;
void capMyString(char * ptr) // creates an function that caps the first letter of each sentence
{
int space = 0;
int period = 0;
*ptr = toupper(*ptr); // capitalizes the first letter
cout<< *ptr; // prints out each letter
for(int i =1; i < strlen(ptr); i++) // computes as long as it is less than the length
{
if(space == 1 && period == 1)
{
*(ptr+1) = toupper(*(ptr+i)); // captializes each letter after a space AND period
cout << *(ptr+1);
period =0;
space = 0;
}
else
{
cout<< (*(ptr+i));
if(period ==1)
{
if(*(ptr+i) == ' ')
{
space = 1;
}
else
{
period = 0;
}
}
else
{
if(*(ptr+i) == '.')
{
period = 1;
}
else
{
period =0;
}
}
}
}
}
int main()
{
constint SIZE = 100; // creates a constant
char text[SIZE]; // creates an array of size 100
cout << "Please enter a string of text: " << endl; // prompts user to enter in a string of text
cin.getline(text,SIZE); // gets the length of the text from the user
capMyString(text);
return 0;
}