在c中验证字符串

时间:2012-10-21 10:24:48

标签: c

我有一个字符串数组

我想要做的是检查字符串是否只包含数字,如果没有给出错误:你输入了字符串

void checkTriangle(char *side1[],char *side2[],char *side3[])
{
    int i;

    for(i=0;i<20;i++)
        if(isdigit(side1[i]) == 0)
        {
            printf("You entered string");
            break;
        }

}

什么都不打印?

3 个答案:

答案 0 :(得分:1)

您的参数是指针数组,而不是字符串。 side1的类型应为char*,而不是char*[]

void checkTriangle(char *side1, /* ... */)
{
    /* ... */
}

要处理浮点值,您可以检查字符串的格式。

#include <ctype.h>
#include <stddef.h>

int checkTriangle(const char *s, size_t n) 
{
    size_t i;
    int p1 = 1;

    for (i = 0; i < n; ++i) {
        if (s[i] == '.')
            p1 = 0;
        else if (!isdigit(s[i]) && !p1)
            return 0;
    }

    return 1;
}
顺便说一下,你的功能设计得不是很好。您应该在调用者中打印并且与字符串的大小无关。

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

int checkTriangle(const char *s, size_t n) 
{
    size_t i;

    for (i = 0; i < n; ++i)
        if (!isdigit(s[i])) 
            return 0;

    return 1;
}

int main(void)
{
    char s[32];
    size_t n;

    fgets(s, sizeof s, stdin);
    n = strlen(s) - 1;
    s[n] = '\0';

    if (!checkTriangle(s, n))
        puts("You entered string");

    return 0;
}

如果允许您完全使用标准C库,也可以使用strtod

答案 1 :(得分:1)

我认为你还没有掌握数组和指针的概念

你对char *side1[]的声明与说char **side1是一回事,{{1}}实际上是指针的指针,我猜你的不是你想要的

我认为在开始使用引用参数传递创建函数之前,您应首先使用pass by value。一般来说,学习语言和编程的基础是更好的

答案 2 :(得分:1)

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

  void checkTriangle(char *side1)
  {
    int i;
    int found_letter = 0;
    int len = strlen(side1);

    for( i = 0; i < len; i++)
    {
        if(side1[i] < '0' || side1[i] > '9')
        {
            found_letter = 1; // this variable works as a boolean
            break;
        }
    }
    if(found_letter) // value 0 means false, any other value means true
        printf("You entered a string");
    else
        printf("You entered only numbers");
  }

参数“char * side1”也可以作为“char side1 []”

传递
相关问题