0

I'm trying to write some code that will take input, loop through the characters in the input, and print "hi" for every "a" that shows up in the input.

I'm getting errors trying to compare the looped characters in the string to "a". I'ts a problem with comparing pointers and integers.

How can I avert this problem (by either changing the types of the variables present or something?)

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

string name;
char x;
char *y;

int main(void){
    printf("Name:");
    name = GetString();
    printf("\n");
    if (name != NULL){
        for (int i = 0, n = strlen(name); i < n; i++)
        {
            x = name[i];
            y = "a"; 
            if (x == y){
                printf("hi");
            }

        }
    }
}

1 Answer 1

1

Your problem is much more basic and simple. Look at these lines:

char x;          // a char variable
char *y;         // a pointer to a string
y = "a";         // loads a string into memory at y
if (x == y){     // compares a char and a string

y is a pointer to a string, not a character. You are attempting to compare a char to a pointer. There are two different ways to fix this. Both ways involve changing the code so that you are comparing char to char.

One way is to change the test and compare chars. if (x == y[0]){

The other way is to make y a char instead of a pointer to a string. It also requires changing the assignment statement.

char y;
y = 'a';

Note that you use double quotes to assign strings and single quotes to assign single chars.

Both approaches would work, but you could make it more efficient as follows:

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

int main(void){
    printf("Name:");
    string name = GetString();
    printf("\n");
    if (name != NULL)
    {
        for (int i = 0, n = strlen(name); i < n; i++)
        {
            if (name[i] == 'a' )
            {
                printf("hi\n");
            }    
        }
    }
}

This eliminates redundant variables x and y. Also, it brings name inside of main instead of making it a global variable when it doesn't need to be. Global vars should be avoided unless there is good reason to create them, something that will show up in a later exercise.

If this answers your question, please click the check mark to accept this and remove the question from the unanswered pool. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .