注册 登录
编程论坛 C++教室

C++怎么里怎么提取字符串"0,110,220|1,143,223|0,446,883" 的坐标

a329367512 发布于 2016-08-09 16:36, 2080 次点击
怎么里怎么提取字符串"0,110,220|1,143,223|0,446,883" 的坐标,我要提取110,220这用x,y表示 ,143,223用x1,y1表示,446,883用x2,y2表怎么提取呢
4 回复
#2
rjsp2016-08-09 19:38
sscanf最简单
#3
rjsp2016-08-10 08:24
程序代码:
#include <cstdio>

int main( void )
{
    const char* s = "0,110,220|1,143,223|0,446,883";

    int x0,y0, x1,y1, x2,y2;
    if( sscanf(s,"%*d , %d , %d | %*d , %d , %d | %*d , %d , %d", &x0,&y0, &x1,&y1, &x2,&y2) == 6 )
        printf( "(%d,%d) (%d,%d) (%d,%d)\n", x0,y0, x1,y1, x2,y2 );
    else
        puts( "error" );

    return 0;
}

输出:(110,220) (143,223) (446,883)
#4
rjsp2016-08-10 08:36
用C++的istream就烦多了
程序代码:
#include <iostream>
#include <sstream>

int main( void )
{
    const char* s = "0,110,220|1,143,223|0,446,883";

    bool bSuccess = false;
    int x0,y0, x1,y1, x2,y2;
    {
        int i0, i1, i2;
        char c0,c1,c2,c3,c4,c5,c6,c7;
        std::istringstream is( s );
        is >> std::skipws;
        if( is>>i0>>c0>>x0>>c1>>y0>>c2>>i1>>c3>>x1>>c4>>y1>>c5>>i2>>c6>>x2>>c7>>y2
            && c0==',' && c1==',' && c2=='|'
            && c3==',' && c4==',' && c5=='|'
            && c6==',' && c7==',' )
        {
            bSuccess = true;
        }
    }

    if( bSuccess )
        std::cout << '('<<x0<<','<<y0<<") ("<<x1<<','<<y1<<") ("<<x2<<','<<y2<<')' << std::endl;
    else
        std::cerr << "error\n";

    return 0;
}

#5
asdzxc5202502016-08-15 15:44
1