C ++简单的字符串解析并保存到整数

时间:2016-04-15 05:50:23

标签: c++

我有一个看起来像这样的字符串,

x:12812Y:121Z:1292

总有“X:”,“Y:”和“Z:” 我需要将每个字母后面的数字转换为int变量,因此

int x = 12812
int y = 121
int y = 1292

有办法吗? 谢谢!

6 个答案:

答案 0 :(得分:0)

是的,有办法做到这一点:

读取两个字符(X:部分),然后读取整数。再重复两次。

如果“string”在文件中,我首先建议您将文件中的整行读入std::string(使用例如std::getline),然后使用std::istringstream提取每行的数据。

如果数据的顺序不是固定的(例如X可能并不总是第一个),那么检查第一个字符以查看该数字是什么数据。

如果订单总是固定且相同,您也可以将数字存储在数组或向量中。

答案 1 :(得分:0)

使用标准scanf就像这样简单:

#include<cstdio>

int main() {
    int x, y, z;
    char xx, yy, zz;
    scanf("%c:%d%c:%d%c:%d", &xx, &x, &yy, &y, &zz, &z);
    printf("%d %d %d\n", x, y, z);
    return 0;
}

答案 2 :(得分:0)

如果订单和格式始终是固定的,您可以这样做:

 string str="x:12812Y:121Z:1292";//you might want to convert this to uppercase first

 string xword,yword,zword;

istringstream ss(&str[1]);//put the string read in to string stream, jump the first x

//you may want to this in a loop
::getline(ss,xword,'Y');//will getthe x part,something like :12812
::getline(ss,yword,'Z');//get the y part, the y will not be read here, something like :121
::getline(ss,zword,'X');//get the z part

xword.erase(0,1);//remove the leading colon
yword.erase(0,1);//remove the leading colon
zword.erase(0,1);//remove the leading colon

 // convert the string to int

答案 3 :(得分:0)

试试这个:

#include<iostream>
#include<sstream>
#include<string>

int main()
{
    std::string str = "x:12812Y:121Z:1292";
    std::string::size_type sz;
    std::stringstream ss(str);
    char tmp;
    int x, y, z;

    ss>>tmp;
    ss>>tmp;
    ss>>x;
    ss>>tmp;
    ss>>tmp;
    ss>>y;
    ss>>tmp;
    ss>>tmp;
    ss>>z;

    std::cout<<"x:"<<x<<"\n";
    std::cout<<"y:"<<y<<"\n";
    std::cout<<"z:"<<z<<"\n";

    return 0;
}

<强>输出:

x:12812
y:121
z:1292

答案 4 :(得分:0)

有些事情可以在不依赖图书馆的情况下以惊人的优雅方式完成。 此代码演示了如何使用next_int函数。 next_int只占用9行 - 其余代码演示了如何使用宽字符C-string,char C-string和std :: string(通过来自std :: string :: c_str()的C-string )。

#include <iostream>
#include <string>

// next_int parses a non-negative decimal integer value
// beginning at or after the passed string pointer.
// The pointer is incremented to point to the character
// which follows the parsed digits.
// If no digits follow the passed pointer, a value of
// zero is returned and the pointer is advanced to the
// string's terminating nul.
template <typename C>
inline int next_int(const C* &p) {
    while(*p && (*p < C('0') || *p > C('9'))) { ++p; }
    int val = 0;
    while(*p >= C('0') && *p <= C('9')) {
        val = val * 10 + *(p++) - C('0');
    }
    return val;
}

int main() {
    const auto* pws = L"x:12812Y:121Z:1292";;
    int x = next_int(pws);
    int y = next_int(pws);
    int z = next_int(pws);
    std::cout << "(" << sizeof(*pws) << " Wide String) x: " << x << "  y: " << y << "  z: " << z << '\n';

    const char* pcs = "54321,891011,0,1";
    std::cout << "\n* char String\n";
    for(int index=0; *pcs; ++index) {
        const int value = next_int(pcs);
        std::cout << "    " << index << ": " << value << '\n';
    }

    // This example shows what happens when no digits follow the pointer
    // passed to next_int.  Because no digits appear in the characters 
    // following the final "10", the last call to next_int returns 0.
    // next_int could be modified to unambiguously enumerate arbitrarily-sized
    // sets of numbers, possibly by returning a magic number (like -1) if
    // val was never updated by a digit, or adding a second scan, advancing
    // p to the next digit or nul character, thus skipping the phantom
    // parse at the end.
    std::string nums = "Flight 552 to Paris cost me $400 1-way and lasted 10 hours";
    const auto* pstr = nums.c_str();
    std::cout << "\n* char String from std::string\n";
    std::cout << "  The extra 0 at the end comes from passing next_int a string containing no digits\n";
    for(int index=0; *pstr; ++index) {
        const int value = next_int(pstr);
        std::cout << index << ": " << value << '\n';
    }
}

这是输出:

(2 Wide String) x: 12812  y: 121  z: 1292

* char String
    0: 54321
    1: 891011
    2: 0
    3: 1

* char String from std::string
  The extra 0 at the end comes from passing next_int a string containing no digits
0: 552
1: 400
2: 1
3: 10
4: 0

答案 5 :(得分:0)

假设键是区分大小写的字母,值总是整数,键和值之间的关系很重要,但键/值对的顺序不重要。

#include <string>
#include <sstream>
#include <iostream>

int main()
{
    std::istringstream ss("x:12812Y:121Z:1292");

    int x, Y, Z;

    while (!ss.eof())
    {
        char tag, delim;
        int val;

        ss >> tag >> delim >> val;

        switch(tag)
        {
            case 'x': x = val; break;
            case 'Y': Y = val; break;
            case 'Z': Z = val; break;
        }
    }

    std::cout << "parsed: x=" << x << " Y=" << Y << " Z=" << Z << std::endl;
    return 0;
},