简体   繁体   中英

Parse a string and assign it to different char

I want to parse a string into a note and octave. For example if the user inputs "A#4", (A#)-note that will be stored in (char n) and (4)- octave that will be stored in (char o). Why am I getting blanked line instead of 4 as output after A#?

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

int main()
{
    string src = get_string();
    char *n;
    char *o;
    char *note = "ABCDEFG#b";
    char *octave = "12345678";

    o = strtok(src, note);
    n = strtok(src, octave);

    printf("%s\n", n);
    printf("%s\n", o);
}

Output:

A#

Can you please point to error and suggest a solution?

strtok is not the function you want to use in this instance.

When you call it, it alters the string, replacing the character that matches the deliminator with a NUL so you'll lose the character you're looking for as the note. The second time you call it with src , the string will appear empty and it won't find anything - you're meant to call it on subsequent times with the first parameter set to NULL so that it knows you're searching for the next token in the same string.

You might want to use strspn which counts the number of characters that match your set (ie note ) or strpbrk that finds the first character that matches.

Or you could traverse the string yourself and use strchr like this

char *pos;

for(pos=src;*pos!='\0';pos++)
  {
  if(strchr(note,*pos))
    {
    // *pos is a note character
    }
  }

Whatever you use, you'll need to build a new string based on your results as the original string won't have space to put NUL terminators inside to separate out the two parts you're looking for.

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