如何让程序停止读取代码?

时间:2013-12-19 07:50:54

标签: c arrays

我想要做的是:用户输入一个字符串;例如:12345,44,55,66。我创建了一个函数来检查前5个字符是否不是数字,然后程序将输出错误消息,如果第6个字符不是,,程序也将输出错误消息。我的问题是,如果检测到错误,我希望程序停止读取代码(如果出现错误则不会打印)。那么我怎么能阻止程序继续阅读代码呢?这是我到目前为止所写的内容。

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

void checkstudentID(char temp[]);

main()
{
    char temp[10000];
    char m0[10000];
    gets(temp);
    checkstudentID(temp);   
    printf("%s",temp);          
    return 0;
}

void checkstudentID(char temp[])
{
    int i;
    for (i=0;i<6;i++)
    {
        if (isdigit(temp[i]) == 0)
        {
            printf("Student ID must contain only integers.\n");
            return 0;
        }
    }
    if (temp[6] != *(","))
    {
              printf("Student ID must contain only 6 integers.\n");
              return 0;
    }
}

3 个答案:

答案 0 :(得分:1)

不要制作多个退出点这是一个好习惯。因此,在子功能中使用exit()并不是一个好习惯。我建议让子函数返回值,告诉它们的状态为主函数。


#include <stdio.h>
#include <string.h>
#include <ctype.h>
int checkstudentID(char temp[]);
void main()
{
    char temp[10000];
    char m0[10000];
    gets(temp);
    switch(checkstudentID(temp))
    {
        case 0: printf("%s",temp);break;
        case 1: printf("Student ID must contain only integers.\n"); break;
        case 2: printf("Student ID must contain only 6 integers.\n"); break;
    }
}

int checkstudentID(char temp[])
{
    int i;
    int ID_status = 0;
    for (i=0;i<6;i++)
        if (0==isdigit(temp[i]))
        {
            ID_status = 1;
            break;
        }
    if (temp[6]!=',') ID_status = 2;
    return ID_status;
}

答案 1 :(得分:0)

使用exit()停止阅读代码。你可以这样做

void checkstudentID(char temp[])
{
int i;
for (i=0;i<6;i++)
{
    if (isdigit(temp[i])==0)
    {
        printf("Student ID must contain only integers.\n");
        exit(0);
    }
}
if (temp[6]!=','))
{
          printf("Student ID must contain only 6 integers.\n");
          exit(0);
}
}

答案 2 :(得分:-2)

另一种只读6个字符的方法是:

//gets(temp);
scanf("%6s", temp);

即使用户输入的字符超过6个,temp也只会存储6个字符。