【问题标题】:Two questions about basic C programs关于基本C程序的两个问题
【发布时间】:2019-01-30 02:46:57
【问题描述】:

1.

如果 3 字符密码包含数字,则将 hasDigit 设置为 true。

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>

int main(void) {
   bool hasDigit;
   char passCode[50];

   hasDigit = false;
   strcpy(passCode, "abc");

   /* Your solution goes here  */

   if (hasDigit) {
      printf("Has a digit.\n");
   }
   else {
      printf("Has no digit.\n");
   }

   return 0;
}

我尝试过的(代替 /* 你的解决方案放在这里 */ 是:

if (isdigit(passCode) == true) {
    hasDigit = true;
}
else {
    hasDigit = false;
}

测试时

abc

它可以工作,但是在测试时

a 5

它不起作用。

2.

将 2 字符字符串 passCode 中的任何空格 ' ' 替换为 '_'。给定程序的示例输出:

1_

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

int main(void) {
char passCode[3];

   strcpy(passCode, "1 ");

   /* Your solution goes here  */

   printf("%s\n", passCode);
   return 0;
}

我代替 /* 你的解决方案在这里 */ 是:

   if (isspace(passCode) == true) {
      passCode = '_';
   }

而且编译失败。

感谢大家的帮助。

【问题讨论】:

  • isdigit(...) 接受一个字符,但您传递的是一个数组。尝试遍历每个字符并传递passCode[i]
  • isdigit(passCode[i]) 导致编译器告诉我: 在 main.c:4:0: main.c 包含的文件中:在函数'main'中:main.c:13: 25: error: 'i' undeclared (first use in this function) if (isdigit(passCode[i]) == true) { ^ main.c:13:25: 注意:每个函数只报告一次未声明的标识符它出现在
  • 也不需要== true,如果是真的,if 会检测到
  • @SOMEK 你需要声明int i; 并初始化它,创建一个for(int i=0; i&lt;3; i++) 循环来检查数组中的每个字符
  • 查看文本或教程中的循环控制。它是基本的 C 语言(以及几乎任何其他语言),您将在余下的工程职业生涯中只使用它。错误很明显:你没有声明你的循环控制变量i(如果你甚至编写了一个循环;我们不知道)。

标签: c


【解决方案1】:

isdigit 函数将int 作为参数,而不是char *。所以你不能通过passCode。您必须遍历passCode 并使用isdigit 测试passCode 中的每个字符。

例如:

bool hasDigit = false;

for (size_t i = 0; passCode[i]; ++i) {
    if (isdigit((unsigned char)passCode[i])) {
        hasDigit = true;
        break;
    }
}

...

注意isdigit(和所有&lt;ctype&gt;函数)不一定返回1,所以与true比较是不正确的。只需检查它是否返回 0 或非零 - 这就是 isdigit 记录返回的内容。

您将对第二个问题使用类似的循环并执行以下操作:

for (size_t i = 0; passCode[i]; ++i) {
   if (isspace((unsigned char)passCode[i])) {
      passCode[i] = '_';
   }
}

【讨论】:

  • 谢谢,这个解决方案有效。 “size_t”的目的是什么,为什么必须指定unsigned char,指定它对程序有何改变?
  • 这个好的答案提供的信息比 OP 可能要求的更多。
  • @WeatherVane 我正在努力学习,所以更多信息很棒!
【解决方案2】:

下面是你将如何使用 for 循环;

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>

int main(void) {
   bool hasDigit;
   char passCode[50];

   hasDigit = false;
   strcpy(passCode, "abc");

   /* Your solution goes here  */
   for (int i=0; passCode[i]; i++)
       if (isdigit(passCode[i]))
           hasDigit = true;

   if (hasDigit) {
      printf("Has a digit.\n");
   }
   else {
      printf("Has no digit.\n");
   }

   return 0;
}

【讨论】:

  • 感谢您的帮助,此解决方案有效。 for 循环的 i=0 和 i++ 部分如何影响它的工作方式?
  • for循环的结构是这样的for ( initial_condition; terminating_condition; post_action ) { body }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多