我想转换单词的情况" welcome"来自给定的字符串。 所有事件都应该已经改变。 我试过的是代码,
#include "stdio.h"
#include <string.h>
#include "ctype.h"
int main(int argc, char const *argv[]) {
printf("Enter the sentence you need to display via app:\n");
char sentence[100];
char word[10] = {"welcome"};
scanf("%[^\n]s", sentence);
getchar();
char * pch;
pch = strtok (sentence," ,.-");
while (pch != NULL)
{
if (strcmp(pch,word) == 0) {
while(*pch != '\0'){
*pch = toupper(*pch);
}
}
printf("%s\n", pch);
pch = strtok (NULL," ,.-");
}
printf("%s\n", sentence);
return 0;
}
/*
Output:
Enter the sentence you need to display via app:
welcome here welcome there
*/
该计划需要永远,并没有按预期工作。 提前谢谢。
答案 0 :(得分:1)
在你的while循环中,你缺少增加字符串的指针。在下面的示例中,我在这里使用临时变量来更新整个字符串。之后可以将ptr
变量用于打印目的。
if (strcmp(pch,word) == 0) {
char *tmp = pch;
while (*tmp != '\0'){
*tmp= toupper(*tmp);
tmp++; //Increase pointer
}
}
答案 1 :(得分:1)
您的计划中存在许多问题:
#include <stdio.h>
中标准包含文件的语法,使用<
和>
代替"
。
您应该将word
定义为指针:const char *word = "welcome";
或不带长度的数组,让编译器为您计算:char word[] = "welcome";
。
scanf
字符范围的语法为%[^\n]
,没有尾随s
。您应将限制指定为%99[^\n]
。
scanf()
将失败。您应该测试返回值,以避免在读取失败时出现未定义的行为。
使用fgets()
读取输入行会更安全。
你不会在循环中增加pch
,因此无限循环需要永远执行。
toupper
不得传递裸char
,您必须将char
转换为unsigned char
,以避免产生未定义行为的潜在负值。
strtok
修改了sentence
,打印时只打印第一个单词(以及任何前面的分隔符)。
以下是更正后的版本:
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[]) {
char sentence[100];
char word[] = "welcome";
printf("Enter the sentence you need to display via app:\n");
if (fgets(sentence, sizeof sentence, stdin)) {
char *pch = strtok(sentence, " ,.-");
while (pch != NULL) {
if (strcmp(pch, word) == 0) {
char *p;
for (p = pch; *p != '\0'; p++) {
*p = toupper((unsigned char)*p);
}
}
printf("%s ", pch);
pch = strtok(NULL," ,.-");
}
printf("\n");
}
return 0;
}