字符串和sscanf [英] String and sscanf

查看:84
本文介绍了字符串和sscanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

int main() {
    char str[] = "My first book";
    char *a, *b, *c;
    sscanf(str, "%s %s %s", a, b, c);
    printf("a=%s b=%s c=%s", a, b, c);
}

我想要输出:a =我的b =第一和c =书。我遇到段错误。为什么?

I want the output: a=My b=first and c=book. I am getting seg fault. Why?

推荐答案

您尚未初始化 a b c

所以这样做

char a[100], b[100], c[100]

此外,您还需要检查 sscanf 的返回值-请查看手册页

Also you need to check the return value from sscanf - Please check out the manual page

格式字符串不正确

 "%[^ ] %[^ ] %[^ ]"

详细信息也在手册页上

sscanf

编辑

如果您不知道字符串的长度,请这样做

If you do not know the length of the string then do

char *a, *b, *c;
size_t len = strlen(str) + 1;
a = malloc(len);
b = malloc(len);
c = malloc(len);

...

free(a);
free(b):
free(c);

这篇关于字符串和sscanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆