C 如何使用i'编写代码来拒绝非数字输入;我试过argv[1][i]它似乎不起作用
嘿,伙计们,我不知道我第一次尝试使用intmain(intargc,argv[])时哪里做错了……我只是不知道我是否正确使用了它。这里有一些代码C 如何使用i'编写代码来拒绝非数字输入;我试过argv[1][i]它似乎不起作用,c,cs50,caesar-cipher,C,Cs50,Caesar Cipher,嘿,伙计们,我不知道我第一次尝试使用intmain(intargc,argv[])时哪里做错了……我只是不知道我是否正确使用了它。这里有一些代码 这段代码编译得很好,并且也正确地给出了结果 使用4作为密钥将“BaRFoo”加密为“FeVJss” 日志 正在运行。/凯撒4。。。 正在发送输入BaRFoo。。。 正在检查输出“密文:FeVJss\n” *****但当我输入2r或4w或任何非数字键时,我的问题是,它会给我以下信息:*** :(处理非数字键 等待程序退出时超时 有谁能告诉我如何为这个函数
#include <string.h>
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
// Variable declarations
bool keySuccessful = false;
int key = 0;
int input_length = 0;
string text = "" ;
// The number of command line args submitted was incorrect.
do
{
if(argc != 2)
{
printf("Usage: ./caesar key .\n");
return 1;
}
else
{
// Convert ASCII char to a alphabate char
// Access individul char in the string plain
// get the key val and converted to integer
key = atoi(argv[1]);
keySuccessful = true;
printf("%s",argv[1]);
}
}
while(!keySuccessful);
// get user input
text = get_string("%s",text);
printf("ciphertext: ");
input_length = strlen(text);
for (int i=0; i<input_length; i++)
{
// Checking if is the lowercase a=97 to z=112
// Print out lower case with ky a=65 to z=90
if(isupper(text[i]))
{
printf("%c", (((text[i] - 65) + key) % 26) + 65);
}
else if(islower(text[i]))
{
printf("%c", (((text[i] - 97) + key) % 26) + 97);
}
else
{
printf("%c", text[i]);
}
}
printf("\n");
return 0;
}
#包括
#包括
#包括
#包括
#包括
int main(int argc,字符串argv[])
{
//变量声明
bool-keysuccesful=false;
int键=0;
int输入_长度=0;
字符串文本=”;
//提交的命令行参数数不正确。
做
{
如果(argc!=2)
{
printf(“用法:./caesar键。\n”);
返回1;
}
其他的
{
//将ASCII字符转换为alphabate字符
//访问纯字符串中的单个字符
//获取键val并转换为整数
key=atoi(argv[1]);
keysuccesful=true;
printf(“%s”,argv[1]);
}
}
而(!keysuccess);
//获取用户输入
text=获取字符串(“%s”,text);
printf(“密文:”);
输入长度=strlen(文本);
对于(int i=0;i如果我正确理解了您的问题,您需要确保第一个参数是数字,否则停止执行。
您可以很容易地在参数上循环,并从ctype.h
检查每个字符的isdigit()
输出,如下所示:
int argumentIsNumber = 1;
for (int i = 0; i < strlen(argv[1]); i++) {
if (isdigit(argv[1][i]) == 0) {
argumentIsNumber = 0;
}
}
if (argumentIsNumber == 0) {
// Tell the user the introduced key is wrong
}
int argumentIsNumber=1;
对于(int i=0;i
如本例所示,您可以将标志设置为1,并在找到非数字时将其更改为0。然后,当循环结束时,如果所有字符都是数字,则标志只能设置为1
希望有帮助!如果用户提示类似的内容,您应该编写代码
美元/凯撒20倍
你应该打印
用法:./caesar键
for (int i = 0 , n = strlen(argv[1]); i < n; i++)
{
if (isalpha(argv[1][i]))
{
printf("Usage: ./caesar key\n");
return 1;
}
}
for(inti=0,n=strlen(argv[1]);i
tyvm我尝试使用这个for循环,但用错误消息保持prmopt me,消息说:caesar.c:40:12:error:relational comparison result unused[-Werror,-Wunused comparison]for(iisdigit(argv[1][i])!=0
也告诉我未定义declaration@echooca别忘了#包括很多我又看了一遍,有一个错误:)如果参数是6567562635265365365363625363643675 68937 3652645 73674,你会认为这个论点是正确的,但是ATOI不会成功。正确的方法不是那个,而且你不管理负数你想做与以前的答案不同的事情,但是你的做法是错误的,例如你认为德12@34作为有效数字。读取isalpha
specification@brunotks对于贡献不确定您是否仍然可以看到我对封闭问题的答复忘记标记您,因此只想在此处发送我的感谢信息查看strtol
以确保参数是有效数字并获取其值,切勿使用atoi