本文介绍了如何识别导致细分错误的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码的目的是接受2个命令行参数(包括程序名),并根据给定的第2个命令行参数打印出所示的响应.如果命令行参数是整数,则用户的输入被接受或成功",并且如果它是其他任何值(例如,字符串或多个命令行参数),则其将为Null并且将显示错误消息.这是CS50凯撒适合熟悉的人的

My code's aim is to take in 2 command line arguments (inclusive of programme name), and to print out responses as shown based on the given 2nd command line argument. If the command line argument is an integer, the user's input is accepted or "Success"and if it as anything else (e.g. a string or more than one command line argument), it will be Null and the error message will be shown. This is for CS50 caesar for those who are familiar

我的代码如下:

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

int main(int argc,string argv[])
{

    char *x = argv[1];
    if (argc == 2 && isdigit(x))
    {
        printf("Success\n");
    }
    else
    {
        printf("Usage: ./caesar key\n");
    }

}

代码可以编译,但是出现段错误.我知道分段错误是程序试图访问为数组分配的内存之外的内容(如果我错了,请纠正我),但是我确实指定了argv [1].

The code compiles but I am given a segmentation fault. I am aware segmentation fault is the programme trying to access something outside of the allocated memory for the array (correct me if I am wrong) but I did specify argv[1].

推荐答案

isdigit 以一个

您可以用来检查第一个参数的第一个字符是否为数字

What you could use to check if the first character of the first argument is a digit is

isdigit((unsigned char)x [0]))

但是最后,您想要的不是检查其中的任何数字,而是将字符串转换为整数,并查看是否发生错误-;然后检查结果值的范围.

but in the end what you want is not to check if any of these are digits, but to convert the string to an integer, and see if an error occurs - use strto(u)l for x and see if it succeeded; then check the range of the resulting value.

这篇关于如何识别导致细分错误的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 11:03
查看更多