有关基本C程序的两个问题

时间:2018-08-23 16:41:56

标签: c

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 = '_';
   }

它无法编译。

感谢所有帮助。

2 个答案:

答案 0 :(得分:1)

isdigit函数使用int作为参数,而不是char *作为参数。因此,您无法通过passCode。您必须遍历passCode并使用passCode测试isdigit中的每个字符。

例如:

bool hasDigit = false;

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

...

请注意,isdigit(和所有<ctype>函数)不一定返回1,因此与true进行比较是不正确的。只需检查它是否返回0或非零-这就是记录isdigit返回的内容。

对于第二个问题,您将使用类似的循环并执行:

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

答案 1 :(得分:1)

这是使用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;
}
相关问题