这是用于学校作业。此功能的目的是从每个数组中随机选择一个单词,然后创建一个新数组,每个句子的首字母大写,每个单词之间的空格以及最后20次的句点。该句子的格式为冠词,名词,动词,介词,冠词和名词。
我的问题是我该如何大写每个句子的首字母?我试图将字符串中的第一个位置设置为等于该位置的char-32,但这只会使程序崩溃。
void randomize(void) {
char *article[] = {"the", "a", "one", "some", "any"};
char *noun[] = {"boy", "girl", "dog", "town", "car"};
char *verb[] = {"drove", "jumped", "ran", "walked", "skipped"};
char *preposition[] = {"to", "from", "over", "under", "on"};
char *sentence[6];
int running = 1;
while(running){
int location = rand()%5;
char *captFirstLetter = article[location];
captFirstLetter[0] = captFirstLetter[0] - 32 ;
sentence[0] = captFirstLetter;
sentence[1] = noun[rand()%5];
sentence[2] = verb[rand()%5];
sentence[3] = preposition[rand()%5];
sentence[4] = article[rand()%5];
sentence[5] = noun[rand()%5];
for(int i = 0; i < 7; i++){
printf("%s%s%s", (i == 6) ? "" : sentence[i], (i > 4) ? "" : " ", (i == 5)? ".\n" : "" );
}
running ++;
if(running == 21){
running = 0;
}
}
}
答案 0 :(得分:5)
哦,不,不,不-SegFault:
使用以下命令创建指向 String Literal 的指针:
char *captFirstLetter = article[location];
您不能修改article
中的指针引用的字符串文字。您尝试修改它们,例如
captFirstLetter[0] = captFirstLetter[0] - 32 ;
调用未定义行为,很可能会立即调用SegFault。字符串文字存储在只读存储器中,并且不能更改(除了最古老和晦涩的硬件以外的所有语言)
要解决此问题,请确保article
指向的字符串是数组,而不是字符串文字。例如,将article
声明为具有足够大小的2D数组:
char article[][8] = {"the", "a", "one", "some", "any"};
此外,当您正确减去32
以翻转第6位(小写位已关闭)时,标准库在toupper()
中提供了宏<ctype.h>
来处理这种情况进行适当的检查以确保大小写更改限制为小写字母。例如:
#include <ctype.h>
...
captFirstLetter[0] = toupper(captFirstLetter[0]);
最后,将其放到一个简短的示例中,以解释上述两个问题,您将:
#include <stdio.h>
#include <ctype.h>
int main (void) {
char article[][8] = {"the", "a", "one", "some", "any"};
size_t n = sizeof article / sizeof *article;
int location = 2;
char *captFirstLetter = article[location];
captFirstLetter[0] = toupper(captFirstLetter[0]);
for (size_t i = 0; i < n; i++)
puts (article[i]);
}
使用/输出示例
$ ./bin/cmplitp2a
the
a
One
some
any
如果您还有其他问题,请告诉我。