Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

c - Checking for repeated characters not giving me the desired output

I am trying to use the below code I have written to firstly check if any character in the alphabet has been repeated in string argv[1] regardless if it is upper or lower case. It keeps spitting out a result that I have a duplicate even when I feed it with a command line argument that contains no duplicated characters.

#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
");
        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
");
        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!
");
            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;

    }

question from:https://stackoverflow.com/questions/65903652/checking-for-repeated-characters-not-giving-me-the-desired-output

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're using isupper(argv[1][Argv_letters]) == isupper(argv[1][k]) which checks that two letters have the same case.

You need to use toupper(argv[1][Argv_letters]) == toupper(argv[1][k]) to check that the two chars represent the same letter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...