区分字符串中的数字和字母

时间:2016-05-28 12:53:58

标签: c

我正在尝试在visual studio中的服务器和客户端之间建立TCPIP通信,客户端将接受来自键盘的字符串,并且只有当数字不是字母表时他才会将字符串发送到服务器我试过在代码下面,但似乎有问题。

while (rc == SOCKET_ERROR);                         //try as long till there is connection (no Socket Error)

printf("conected with %s..\n\n", address);


do
{

    printf("Please insert the Blood pressure values for further Diagnostic\n ");
    gets(data);
    char i;
    for (i = data[0]; i <= MAX; i++)
    {

        char n = data[i];
        if ((strlen(data) > MAX) || (strlen(data) == 0)) 
        {

            printf("argument not allowed!\n\n");
            memset(data, '\0', strlen(data));
            continue;

        }
        if ((n >= 'a' && n <= 'z') ||( n >= 'A' && n <= 'Z'))

        {

            printf("you have to enter a number !\n\n");
            memset(data, '\0', strlen(data));                   
            continue;
            //next iteration

        }
    }

3 个答案:

答案 0 :(得分:1)

  1. for (i = data[0]; i <= MAX; i++)我想你会想要初始化&#39; i&#39;使用0而不是数据[0]并希望以i作为索引遍历数据。导致问题的原因是

  2. 为什么要在循环中执行此操作?它应该是一次性操作:

    if ((strlen(data) > MAX) || (strlen(data) == 0)) 
    {
        printf("argument not allowed!\n\n");
        memset(data, '\0', strlen(data));
        continue;
    }
    
  3. &#39;继续&#39;在第二个if将再次迭代for循环。你想要打破&#39;从这里循环到do-while循环

答案 1 :(得分:0)

for循环是错误的。相反,请尝试:

do{
     int i;
     int flag = 0;
     gets(data);
     if ((strlen(data) > MAX) || (strlen(data) == 0)) 
             {
                  printf("argument not allowed!\n\n");
                  memset(data, '\0', strlen(data));
                  continue;
             }
     for(i = 0 ; i<strlen(data) ; i++){
         if (!isdigit(data[i]))
         {
             printf("you have to enter a number !\n\n");
             memset(data, '\0', strlen(data));                  
             flag = 1;break;
         }
     }
     if(flag){
          continue;
     }
}

答案 2 :(得分:0)

您可以尝试这样的事情:

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

#define MAX 500

int main() {
    char data[100] = { 0 };

    do
    {
        printf("Please insert the Blood pressure values for further Diagnostic\n ");
        if (gets(data) != NULL && strlen(data) <= MAX) {
            for (int i = 0; i < strlen(data); i++) {
                if (!isdigit(data[i])) {
                    printf("you have to enter a number !\n\n");
                }
                else {
                    // process value
                    putchar(data[i]);
                }
            }
        }
        else {
            printf("Invalid argument\n\n");
        }
    } while (1 == 1);  // you would have to decide when to terminate
}