How to change first letter to uppercase in array of pointers to strings?

2.7k views Asked by At

I have arrays of pointers to char arrays as below.

char *ptrArticle[]={"the","a","one","some"};

I am trying to randomize a sentence like this:

"The girl skipped under a boy."

So I have to make first words first character uppercase. But this does not seem to work. Compiler does not give any errors but does not work as intended also. Still lowercase. Can you give me advice?

 toupper(*ptrArticle[articleRandomIndex]);




#include <stdio.h>
#include<stdlib.h>
#include<time.h>
#include <string.h>
#include <ctype.h>

int main(void){

int articleRandomIndex;
int nounRandomIndex;
int verbRandomIndex;
int prepositionRandomIndex;
int secondArticleRandomIndex;
int secondNounRandomIndex;

char sentence[200];
//array of pointers to char arrays
char *ptrArticle[]={"the","a","one","some"};
char *ptrNoun[]={"boy","girl","dog","town","car"};
char *ptrVerb[]={"drove","jumped","ran","walked","skipped"};
char *ptrPreposition[]={"to","from","over","under","on"};
srand(time(NULL));

articleRandomIndex=rand()%4;
nounRandomIndex=rand()%5;
verbRandomIndex=rand()%5;
prepositionRandomIndex=rand()%5;
secondArticleRandomIndex=rand()%4;
secondNounRandomIndex=rand()%5;

toupper(*ptrArticle[articleRandomIndex]);

strcpy(sentence,ptrArticle[articleRandomIndex]);
strcat(sentence," ");
strcat(sentence,ptrNoun[nounRandomIndex]);
strcat(sentence," ");
strcat(sentence,ptrVerb[verbRandomIndex]);
strcat(sentence," ");
strcat(sentence,ptrPreposition[prepositionRandomIndex]);
strcat(sentence," ");
strcat(sentence,ptrArticle[secondArticleRandomIndex]);
strcat(sentence," ");
strcat(sentence,ptrNoun[secondNounRandomIndex]);
strcat(sentence,".");

puts(sentence);

getch();

}
3

There are 3 answers

1
Some programmer dude On BEST ANSWER

First of all, the toupper function returns the upper case character.

Secondly, why not simply do toupper on the first character in the string you construct?

E.g.

sentence[0] = toupper(sentence[0]);
puts(sentence);

This way you can use your randomizing code multiple times without modifying the actual string you use for the construction of the sentence. Also, then you won't try to modify a string literal, which is read only.

0
unxnut On

toupper returns the character; it does not modify the input. You need to save the output from toupper.

0
haccks On

The problem is that toupper returns a character (uppercase) and you are not storing that character by assuming that it will change the first letter of ptrArticle[]={"the","a","one","some"}; by doing

toupper(*ptrArticle[articleRandomIndex]);

only!