I am trying to convert a fraction string (X/Y) into integers, however, I am having trouble. I made my function dynamic meaning X and Y can be any length.

Here is my code:

int duration(string fraction)

//take in fraction "X/Y"
//assumes num and den are any digit
//return number of eighth note counts it is

//find the position of slash in fraction
int length = strlen(fraction);
string slash = strchr(fraction, '/');
int slash_pos = (int)(slash-fraction);

//using that, you can find substring num_s
string num_s[slash_pos+1];
memcpy(num_s, &fraction[0], slash_pos);
num_s[slash_pos] = "\0";

//likewise, find substring den_s
string den_s[length - slash_pos-1];
memcpy(den_s, &fraction[slash_pos], length-slash_pos-1);
den_s[length-slash_pos-2] = "\0";

//convert to ints
int denominator = atoi(den_s);
int numerator = atoi(num_s);

//find number of eight notes
int eighth_notes = 8*(numerator/denominator);
return eighth_notes;

I get an error when it goes from converting the string of the numerator and denominator into an integer using atoi. The error says

"incompatible pointer types passing 'const char *[slash_pos + 1]' to parameter of type 'const char *' " and "incompatible pointer types passing 'const char *[length - slash_pos - 1]' to parameter of type 'const char *'"

It is probably due to the "memcpy" function; ultimately I want to extract a substring from the string "X/Y".

~Thank you in advance <3


Have you looked at the function strncpy()?

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

  • Hello Cliff! strncpy does not take in a parameter that allows me to copy a part of the string given some index. For example for the string "41/17" I want to get the string "41" and the string "17". I do not know how strncpy can extract the substring "17". – faelesterio Jun 24 '18 at 21:39
  • I assume that the "/" is the delineator. Find it's position, calculate the length and starting positions of the two substrings and call strncpy using those values. Don't forget to also add the EOS marker to the extracted substrings afterwards. – Cliff B Jun 24 '18 at 21:51

You must log in to answer this question.

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