gpt4 book ai didi

C if 语句,检查特殊字符和字母的最佳方法

转载 作者:行者123 更新时间:2023-12-02 02:04:23 24 4
gpt4 key购买 nike

大家好,提前感谢您的帮助,我正在学习 CS50 类(class),我正处于编程的最初阶段。

我正在尝试检查主函数参数string argv[]中的字符串是否确实是一个数字,我搜索了多种方法。我在另一个主题中找到How can I check if a string has special characters in C++ effectively? ,关于用户 Jerry Coffin 发布的解决方案:

char junk;
if (sscanf(str, "%*[A-Za-z0-9_]%c", &junk))
/* it has at least one "special" character
else
/* no special characters */

如果在我看来它可能适合我想做的事情,我不熟悉 sscanf 函数,我很难集成和适应我的代码,我到目前为止我无法理解我的错误的逻辑:

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

int numCheck(string[]);

int main(int argc, string argv[]) {
//Function to check for user "cooperation"
int key = numCheck(argv);
}

int numCheck(string input[]) {
int i = 0;
char junk;
bool usrCooperation = true;

//check for user "cooperation" check that key isn't a letter or special sign
while (input[i] != NULL) {
if (sscanf(*input, "%*[A-Za-z_]%c", &junk)) {
printf("test fail");
usrCooperation = false;
} else {
printf("test pass");
}
i++;
}
return 0;
}

最佳答案

check if the string from the main function parameter string argv[] is indeed a number

测试字符串是否转换为int的直接方法是使用strtol()。这可以很好地处理“123”、“-123”、“+123”、“1234567890123”、“x”、“123x”、“”。

int numCheck(const char *s) {
char *endptr;
errno = 0; // Clear error indicator
long num = strtol(s, &endptr, 0);
if (s == endptr) return 0; // no conversion
if (*endptr) return 0; // Junk after the number
if (errno) return 0; // Overflow
if (num > INT_MAX || num < INT_MIN) return 0; // int Overflow
return 1; // Success
}

int main(int argc, string argv[]) {
// Call each arg[] starting with `argv[1]`
for (int a = 1; a < argc; a++) {
int success = numCheck(argv[a]);
printf("test %s\n", success ? "pass" : "fail");
}
}

sscanf(*input, "%*[A-Za-z_]%c", &junk) 是测试数值转换的错误方法。

关于C if 语句,检查特殊字符和字母的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68643399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com