C ++,如何标记这个字符串? [英] C++, how to tokenize this string?

查看:148
本文介绍了C ++,如何标记这个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它们以空格分隔,我如何得到Ac milan和Real Madryt这样的字符串?

How can I get string like "Ac milan" and "Real Madryt" if they are separated with whitespace?

这是我的尝试:

string linia = "Ac milan ; Real Madryt ; 0 ; 2";
str = new char [linia.size()+1];
strcpy(str, linia.c_str());
sscanf(str, "%s ; %s ; %d ; %d", a, b, &c, &d);

但不起作用;我有: a = Ac; b =(null); c = 0; d = 2;

but it doesn't work; I have: a= Ac; b = (null); c=0; d=2;

推荐答案

是的,sscanf 可以 '请求,使用scanneret转换:

Yes, sscanf can do what you're asking for, using a scanset conversion:

#include <stdio.h>
#include <iostream>
#include <string>

int main(){ 

    char a[20], b[20];
    int c=0, d=0;
    std::string linia("Ac milan ; Real Madryt ; 0 ; 2");
    sscanf(linia.c_str(), " %19[^;]; %19[^;] ;%d ;%d", a, b, &c, &d);

    std::cout << a << "\n" << b << "\n" << c << "\n" << d << "\n";
    return 0;
}

这样产生的输出是:

Ac milan
Real Madryt
0
2

这篇关于C ++,如何标记这个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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