私がこのような文字列を持っているかどうかを言います
char foo[10] = "%r1%r2";
を取り出して1s2に変換したいint。どうすればこれを行うことができますか?
if (sscanf(foo, "%%r%d%%r%d", &i1, &i2) != 2)
...format error...
あなたがフォーマットをするとき、
sscanf()私は理解し%dているのは10進整数ですが、なぜあなたは持っているの%%rですか?
%ソース文字列でリテラルを探している場合は%%、それをフォーマット文字列で指定するために使用します(そして、printf()では、フォーマット文字列で使用して出力%%にを生成し%ます)。はrそれ自体を表します。
変換を指定する方法は他にもあります。たとえば、%*[^0-9]%d%*[^0-9]%d; 割り当て抑制(*)とスキャンセット([^0-9]、数字以外のもの)を使用します。この情報は、のマニュアルページから入手できるはずですsscanf()。
sscanf()あなたはあなたの結果を得るために使うことができます
文字列には実際には2つの「%」とそれぞれの後に1つの数字があることを考慮してください。例えば:
char foo[10] = "%123%874";
stdlibライブラリを含めることを忘れないでください:
#include <stdlib.h>
次のコードは、123をr1に、874をr2に取得します。
for(int i = 1; ; i++)
if(foo[i] == '%')
{
r2 = atoi(&foo[i + 1]); // this line will transform what is after the second '%' into an integer and save it into r2
foo[i] = 0; // this line will make the place where the second '%' was to be the end of the string now
break;
}
r1 = atoi(&foo[1]); // this line transforms whatever is after the first character ('%') into an int and save it into r1
int array[MAXLEN];
int counter = 0;
for(int i = 0; i < strlen(foo); i++){
if(isdigit(foo[i]) && (counter < MAXLEN)){
array[counter++] = (int)(foo[i]-'0');
}
}
//integers are in array[].