0

我有指向 char 数组的指针数组,如下所示。

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

我正在尝试随机化这样的句子:

“那个女孩跳过了一个男孩。”

所以我必须将第一个单词的第一个字符大写。但这似乎不起作用。编译器不会给出任何错误,但也不能按预期工作。还是小写。你能给我建议吗?

 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();

}
4

3 回答 3

3

首先,toupper函数返回大写字符。

其次,为什么不简单地toupper在你构造的字符串的第一个字符上做呢?

例如

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

这样,您可以多次使用随机化代码,而无需修改用于构建句子的实际字符串。此外,您不会尝试修改只读的字符串文字。

于 2013-09-04T12:19:50.330 回答
1

toupper返回字符;它不会修改输入。您需要将输出保存在toupper.

于 2013-09-04T12:20:11.637 回答
1

问题是toupper返回一个字符(大写),并且您没有通过假设它将更改第一个字母来存储该ptrArticle[]={"the","a","one","some"};字符

toupper(*ptrArticle[articleRandomIndex]);

只要!

于 2013-09-04T12:22:32.450 回答