将输入字符串中的单词 "welcome"更改为大写

标签 c

我想转换给定字符串中单词“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

*/

该程序需要很长时间并且无法按预期工作。 提前致谢。

最佳答案

您的程序存在很多问题:

  • #include <stdio.h> 中标准包含文件的语法,使用<>而不是" .

  • 您应该定义 word作为指针:const char *word = "welcome";或一个没有长度的数组,让编译器为您计算: char word[] = "welcome"; .

  • scanf 的语法字符范围是 %[^\n] ,没有尾随 s 。您应该将限制指定为 %99[^\n] .

  • scanf()如果输入空行将会失败。您应该测试返回值以避免读取失败时出现未定义的行为。

  • 使用 fgets() 会更安全读取一行输入。

  • 您不增加 pch在循环中,因此无限循环需要永远执行。

  • toupper不得裸露char ,您必须转换 charunsigned 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;
}

关于将输入字符串中的单词 "welcome"更改为大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44759468/

相关文章:

c - 如何使用 OpenMP 从 0-1 数组中提取所有非零元素的索引?

c++ - 初始化指向常量数组的指针

c - 在 C 中获取 Fat12 磁盘的卷标

c - fork父子通信

c - getchar() 函数的奇怪行为

c - Linux 中的 Tap 设备无法正确传递 ARP/IP 数据包?

c - 有人问我这段代码有什么问题

c - 如果 argp_program_bug_address 存在或不存在,GNU Argp 如何改变其行为?

c - 尝试将 char[] 存储到 char* 时出现问题

c - 在设备驱动程序中使用 stdlib.h