store two pieces of a string in two other strings

Asked

Viewed 32 times

0

Basically what I need is to make a mini Assembly simulator. the information will be entered by the user thus: MOV A,30

then what I was thinking of doing was storing the first 3 characters of the string in a new string (which in this case would be the first "MOV" command) and storing the part of "A,30" in another, to then separate this last string and get the other 2 commands, but when I type the command, only the first 3 characters (MOV) are shown in the print.

someone knows how I could make it work what I’m doing, or how I could just sort out the 3 pieces of information and store it, without the need to separate it?

Here is the basis of that code:

int main()
{
    char comando[20];
    char comando1[20];
    char comando2[20];
    char comando3[20];
    scanf("%s", &comando);

    memcpy(comando1, &comando[0], 3);

    memcpy(comando2, &comando[3], strlen(comando));

    printf("\n%s %s", comando1, comando2); // essa parte aq é só pra verificar se foi armazenado corretamente

    return 0;

}

1 answer

0

  1. Your reading is wrong. %s will stop at the first blank.
  2. You are copying memory in uninitialized variables that are supposed to be strings, will give problem.
  3. If you know that the first string will be only 3 characters, then the second string should start from position 4, because position 3 is a white space.
int main()
{
    char comando[20];
    char comando1[20] = "";
    char comando2[20] = "";
    char comando3[20];
    scanf("%[^\n]", &comando); //aqui vai ler até o primeiro \n

    memcpy(comando1, &comando[0], 3);

    memcpy(comando2, &comando[3], strlen(comando));

    printf("\n%s %s", comando1, comando2); // essa parte aq é só pra verificar se foi armazenado corretamente

    return 0;
}

But... if you take into consideration what I said in 1.... You could just do:

int main()
{
    char comando2[20];
    char comando3[20];
    scanf("%s %s", comando2, comando3);
}
  • Just adding: if the beginning of your string does not have 3 characters you can break your string using the function strtok of <string.h>.

  • good, better than using Strtok to break in spaces is already read separate as I suggested at the end.

  • For this specific case yes. I just wanted to draw attention to the fact that there is already a function to split a string into tokens.

  • I was doing this to read the 2 separate commands, but it wasn’t working either, so I figured it was because in typing the command there is no ENTER to differ from each other, only a space, so the program would read the 2 commands as only 1, The space would be read as one of the characters. obg for help!!

Browser other questions tagged

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