检查重复的字符没有给我想要的输出
Checking for repeated characters not giving me the desired output
我正在尝试使用我编写的以下代码首先检查字符串 argv[1]
中是否重复了字母表中的任何字符,无论它是大写还是小写。即使我用不包含重复字符的命令行参数输入它,它也会不断吐出我有重复的结果。
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main (int argc, string argv[])
{
//checking to make sure only one command line argument can be inputted
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
//defining key argument and making sure string is a certain length
int key = strlen(argv[1]);
if (key != 26)
{
printf("key is not long enough\n");
return 1;
}
//checking for non alphabetical characters in the key
for(int i = 0; i < key; i++)
{
char n = argv[1][i];
if (isalpha(n) == 0)
{
printf("Your key contains non alpha characters, try again!\n");
return 1;
}
//counting the number of letters in key and storing them in i.
for(int Argv_letters = 0, key_len = strlen(argv[1]); Argv_letters < key_len; Argv_letters++)
{
// making k +1 greater than key letters and adding to k if its less.
for(int k = Argv_letters + 1; k < key_len; k++)
if (argv[1][Argv_letters] == argv[1][k] || isupper(argv[1][Argv_letters]) == isupper(argv[1][k]))
{
printf("we have duplicate");
return 1;
}
}
return true;
}
您正在使用 isupper(argv[1][Argv_letters]) == isupper(argv[1][k])
检查两个字母是否大小写相同。
您需要使用toupper(argv[1][Argv_letters]) == toupper(argv[1][k])
来检查这两个字符是否代表相同的字母。
我正在尝试使用我编写的以下代码首先检查字符串 argv[1]
中是否重复了字母表中的任何字符,无论它是大写还是小写。即使我用不包含重复字符的命令行参数输入它,它也会不断吐出我有重复的结果。
#include <cs50.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main (int argc, string argv[])
{
//checking to make sure only one command line argument can be inputted
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
//defining key argument and making sure string is a certain length
int key = strlen(argv[1]);
if (key != 26)
{
printf("key is not long enough\n");
return 1;
}
//checking for non alphabetical characters in the key
for(int i = 0; i < key; i++)
{
char n = argv[1][i];
if (isalpha(n) == 0)
{
printf("Your key contains non alpha characters, try again!\n");
return 1;
}
//counting the number of letters in key and storing them in i.
for(int Argv_letters = 0, key_len = strlen(argv[1]); Argv_letters < key_len; Argv_letters++)
{
// making k +1 greater than key letters and adding to k if its less.
for(int k = Argv_letters + 1; k < key_len; k++)
if (argv[1][Argv_letters] == argv[1][k] || isupper(argv[1][Argv_letters]) == isupper(argv[1][k]))
{
printf("we have duplicate");
return 1;
}
}
return true;
}
您正在使用 isupper(argv[1][Argv_letters]) == isupper(argv[1][k])
检查两个字母是否大小写相同。
您需要使用toupper(argv[1][Argv_letters]) == toupper(argv[1][k])
来检查这两个字符是否代表相同的字母。