【发布时间】:2021-08-03 22:25:43
【问题描述】:
大家好,提前感谢您的帮助,我正在学习 CS50 课程,我刚刚开始编程。
我正在尝试检查主函数参数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;
}
【问题讨论】:
-
if (sscanf(str, "%*[A-Za-z0-9_]%c", &junk))将是true成功读取和EOF.- 很可能不是你想要的。 -
请用
cs50标记您的问题。string类型是非标准的。本课程正在教坏习惯。 -
在我们尝试回答您的错误的性质之前,您先解释一下您的错误的表现如何?你如何运行程序,你希望看到什么,你实际看到了什么?
-
我会使用
for循环和isdigit()。保持简单。