通过循环通过"isalpha"传递数组

boa*_*ica 1 c arrays loops

我已经在这一段时间了很长一段时间,现有的答案几乎没有帮助.我是编程的新手,我正在尝试编写程序的子部分,试图检查任何给定的输入是否仅由字母组成.

为此,我想到的想法是通过使用一次传递每个字符的循环来传递整个数组通过isalpha函数.这个想法具有逻辑意义,但我在实现它时遇到语法障碍.我将非常感谢任何帮助!

以下是我的代码 -

printf("Please type the message which needs to be encrypted: ");
string p = GetString();

for (int i = 0, n = strlen(p); i < n; i++)
{
   if(isalpha(**<what I'm putting here is creating the problem, I think>**) = true)
   {
      printf("%c", p[i]);
   }

}
Run Code Online (Sandbox Code Playgroud)

gsa*_*ras 6

你应该修改你的代码(假设你自己定义了字符串类型):

printf("Please type the message which needs to be encrypted: ");
string p = GetString();

for (int i = 0, n = strlen(p); i < n; i++)
{
   if(isalpha(p[i]) == true) // HERE IS THE ERROR, YOU HAD =, NOT ==
   {
      printf("%c", p[i]);
   }

}
Run Code Online (Sandbox Code Playgroud)

操作员=用于分配,操作员==用于比较!

那发生了什么?无论如何,任务都是真实的p[i].

正如昆汀所说:

if(isalpha(p[i]) == true)

如果像这样编写,可能会更优雅和错误修剪:

if(isalpha(p[i]))

这是C中的一个例子:

/* isalpha example */
#include <stdio.h>
#include <ctype.h>

int main(void)
{
  int i = 0;
  char str[] = "C++";
  while (str[i]) // strings in C are ended with a null terminator. When we meet
  // the null terminator, while's condition will get false.
  {
    if (isalpha(str[i])) // check every character of str
       printf ("character %c is alphabetic\n",str[i]);
    else
       printf ("character %c is not alphabetic\n",str[i]);
    i++;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

资源

参考isalpha().

C没有字符串类型.

提示:下次发布您的代码!

Allo,正如Alter注意到的那样,使用它会很好:

isalpha((unsigned char)str[i])

并在你的代码中

isalpha((unsigned char)p[i])

出于安全原因.