Doubt regarding string manipulation

Asked

Viewed 55 times

0

I’m starting programming and was trying to do a string manipulation, someone could help me in the code below where I would be missing:

#include <stdio.h>

int main( int, char ** )
{

    char nome[] = "zezinho";
    int i;

    for ( i = 0; i < 500; i++ )
    {
        if ( nome[i]  = "z" );
        nome[i] = "p";
    }
    printf( "%c", nome[i] );

}

In compiler gives an invalid conversion error of const char for char.

  • Wow, it worked perfectly. Thank you very much, but I have so many doubts. I wanted to know 10% of what you know... One day I get there. Thank you again.

1 answer

2

You have several small errors in the code, some of which do not allow you to compile and others are shown only as warnings.

  • int main( int, char ** ) - Each of the parameters of the main and the most common are argc and argv respectively.
  • i < 500 - Your text does not have 500 characters and so from a certain point, when you try to access the character will make invalid accesses in memory. Correct would be exchange for nome[i] != '\0' tested by the terminator, or even using the size of the name obtained with strlen.
  • if ( nome[i] = "z" ); - Comparison is always made with == and not =, and the if never takes ; otherwise has no associated instruction. In addition the delimiter for a char is ' and not ".
  • nome[i] = "p"; - Here’s the same delimiter problem, which should be ' because we are talking about a character and not a text.
  • printf( "%c", nome[i] ); - If the idea is to print the whole name the printing should be done with %s and just passing by nome as an argument.

Corrected code:

#include <stdio.h>

int main(int argc, char **argv)
{
    char nome[] = "zezinho";
    int i;

    for (i = 0; i < nome[i] != '\0'; i++)
    {
        if (nome[i] == 'z')
            nome[i] = 'p';
    }
    printf("%s", nome);
}

Watch it run on Ideone

  • One more question. What would be the way to enter data through the SCANF command. I am using scanf("%c", &name); and returns an error. What would be the right way?

  • For a string it would be: scanf("%s", string); (without & because string is already an address. Note that the first space is considered delimiter and closes the input. To read to the end of the line use: scanf("%[ n]s", string);

  • @Célioeduardo another alternative to what anonymity has already said is to use the fgets to read an entire line although it has more implications and tends to be more complicated. The scanf with %s and its variant of %[^\n]s for an entire row is simpler. Remember that %c is for character and so only allows one letter and the correct type has to be only one char and not a vector of char.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.