sscanf读取字符串中的字符串
我有一个小问题,似乎无法解决。假设我有一根绳子sscanf读取字符串中的字符串,c,string,scanf,C,String,Scanf,我有一个小问题,似乎无法解决。假设我有一根绳子 buffer=“1 X./simple E” 我想提取2个整数,2个字符和文件名 sscanf(缓冲区,“%d%d%c%s%c,&a,&b,&c,d,&e); printf(“%d%d%c%s%c”,a,b,c,d,e); 我没有得到我所期望的结果。我得到了“11 1 X(null)”。感谢您的帮助。c和e可以是int或chars。请注意d[100]的溢出问题 #include <cstdio> #include <cstdlib
buffer=“1 X./simple E”
我想提取2个整数,2个字符和文件名
sscanf(缓冲区,“%d%d%c%s%c,&a,&b,&c,d,&e);
printf(“%d%d%c%s%c”,a,b,c,d,e);
我没有得到我所期望的结果。我得到了“11 1 X(null)”。感谢您的帮助。c和e可以是int或chars。请注意d[100]的溢出问题
#include <cstdio>
#include <cstdlib>
int main() {
char buffer[] = "1 1 X ./simple E", c, d[10], e;
int a, b;
//sscanf(buffer, "%d %d %c %*[./]%s %c", &a, &b, &c, d, &e); //To ignore "./"
sscanf(buffer, "%d %d %c %s %c", &a, &b, &c, d, &e); //Don't ignore "./"
printf("%d %d %c %s %c\n", a, b, c, d, e);
return 0;
}
int a, b, c, e;
char d[100];
sscanf(buffer, "%d %d %c %s %c, &a, &b, &c, d, &e);
printf("%d %d %c %s %c", a, b, c, d, e);
您正在声明
char*d
,该声明将失败,因为它没有有效的指向位置。使用具有足够空间的数组可以执行以下操作:
#include <stdio.h>
#include <string.h>
int main()
{
int a, b;
char c, e;
char d[20];
char buffer[] = "1 1 X ./simple E";
sscanf(buffer, "%d %d %c %s %c", &a, &b, &c, d, &e);
printf("%d %d %c %s %c", a, b, c, d, e);
}
#包括
#包括
int main()
{
INTA,b;
字符c,e;
chard[20];
字符缓冲区[]=“1 X./simple E”;
sscanf(缓冲区,“%d%d%c%s%c”、&a、&b、&c、d和e);
printf(“%d%d%c%s%c”,a、b、c、d、e);
}
输出:
11 X./simple E
在sscanf函数参数中不需要空格分隔符
sscanf(buffer, "%d%d%c%s%c", &a, &b, &c, d, &e);
%d
在读取缓冲区时是空格分隔的,并且%c
和%s
之间不应该有空格,因为它吞掉了空格,使缓冲区在字符和字符串之间没有分隔符。如何声明一个bc d e?a,b是int,c,e是char,d是char*。使d像这样“char d[100];“谢谢大家。以后将添加完整代码。
sscanf(buffer, "%d%d%c%s%c", &a, &b, &c, d, &e);