通过循环通过“isalpha”传递数组

时间:2014-06-03 07:06:16

标签: 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]);
   }

}

3 个答案:

答案 0 :(得分: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]);
   }

}

运算符=用于分配,运算符==用于比较!

那发生了什么事?无论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;
}

Source

isalpha()

Ref

C does not have a string type

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

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

isalpha((unsigned char)str[i])

并在您的代码中

isalpha((unsigned char)p[i])

代表safety reasons

答案 1 :(得分:2)

您的示例是here

即。 isalpha()的参数是字符串p的第i个字符。唯一的问题是如何访问第i个角色。通常你可以使用[]。即只需使用以下代码:isalpha(p[i])(我看到你已经在调用printf时使用了[]。

同样isalpha(p[i]) = true是错误的条件。看起来您计划检查isalpha(p[i]) == true(您可以跳过== true)。

答案 2 :(得分:0)

晚了但是:

其他答案都说省略== true 是可取的,但不要说是便携性所必需的

C核心语言操作符== != < <= > >= && ||返回“逻辑”字符。 value使用int值1表示true,0表示false。在C99及以上stdbool.h以及true为1且false为0之前按惯例约定,例如if( (a < b) == true )将正常工作,虽然它是多余的,许多(包括我)认为它风格很差。 测试逻辑值的语言元素,即if(c) while(c) for(;c;)和操作数到&& ||,左操作数到?:,将任何比较等于0的值视为是的,以及任何其他值都是真的。

ctype.h中的字符分类例程以及feof(f)ferror(f)之类的其他标准库例程被指定为返回某些非零int 表示true,0(表示int)表示false,在许多实现中,用于true的非零值不是(总是)1 。在这些情况下,isalpha(whatever) == true可能会导致测试说4 == 1,即使whatever是字母字符也会失败。如果你真的想写一些明确的东西,OTOH isalpha(...) != falseisalpha(...) != 0确实可以正常工作。