简体   繁体   中英

Checking a command line for string

So, the goal of the project is to ask for the names of the voters in the command line. Then it should prompt the users for the number of people voting. After it should prompt the user for the people to vote for (the amount of times the user in prompted to vote for should be equal to number of voters), if a name that is not mentioned in the command line is entered it should say invalid and reprompt the user. I'm not sure what I'm doing wrong.

Here is an example of how the terminal should look.

$ ./plurality Alice Bob
Number of voters: 3
Vote: Alice
Vote: Charlie
Invalid vote.
Vote: Alice
Alice

Here is my code

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

int x;
int main (int argc, string argv[]) //command line for candidates
{
 int num_vote = get_int("Number of voters: "); //number of voters
 string vote;
 // loop that asks for who to vote for, if name matches argv[] move on, else check through the rest of argv{}
 while ( x < num_vote)
 {
 vote = get_string("Vote: ");
    if (strcmp(argv[x],vote))
    {
     x++;
    }
   //checks all of argv, if nothing found prompts user again and checks again
    else if ((x + 1) == num_vote && (!strcmp(argv[x],vote)))
    {
    printf("Invalid vote.");
    num_vote -= 1;
    }


 }
}

If I am understanding the problem well you are mixing up between the number of electors and the number of people voting.

In the given loop you are using the variable x to loop over to take user's input while in the line if (strcmp(argv[x],vote)) you are using it to access the argv array.

So first you should calculate the number of voters by looping throw argv and then loop over it in every iteration to find out if a giver name is in it or not.

here is my working cSharp code for reprompt incase of wrong input hope it will help

int age;
            Console.WriteLine("\n Enter yhour age");
            
            while (!int.TryParse(Console.ReadLine(), out age))
            {
                Console.WriteLine
                    ("You have entered an invalid number please enter again");
                continue;
            }
            {
                Console.WriteLine
                    ("yourage is " + (age));
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM