[英]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).
例如,如果用户输入“ A#4”,则将(A#)音符存储在(char n)中,而(4)八度音符将存储在(char o)中。 Why am I getting blanked line instead of 4 as output after A#?
为什么在A#之后输出空白行而不是4?
#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. strtok
不是您要在此实例中使用的功能。
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. 调用它时,它会更改字符串,并用
NUL
替换与分隔符匹配的字符,因此您会丢失要查找的字符作为音符。 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. 第二次使用
src
调用该字符串时,该字符串将显示为空,并且不会找到任何内容-您打算在以后的时间使用第一个参数设置为NULL
来调用它,以便它知道您正在搜索下一个令牌在同一字符串中。
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. 您可能要使用
strspn
来计算与您的集合(即note
)匹配的字符数,或者使用strpbrk
来找到strpbrk
匹配的第一个字符。
Or you could traverse the string yourself and use strchr
like this 或者,您可以自己遍历字符串并像这样使用
strchr
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. 无论使用什么方法,都需要根据结果构建一个新的字符串,因为原始字符串没有空间将
NUL
终结符放到里面来分离出您要查找的两个部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.