0

我在使用纯 C++ 拆分字符串时遇到问题

字符串总是这样

12344//1238

第一个 int 然后 // 然后是第二个 int。

需要帮助来获取两个 int 值并忽略 //

4

6 回答 6

1
string org = "12344//1238";

size_t p = org.find("//");
string str2 = org.substr(0,p);
string str3 = org.substr(p+2,org.size());

cout << str2 << " "<< str3;
于 2013-04-26T18:25:55.907 回答
1

为什么我们不能使用 sscanf?

char os[20]={"12344//1238"};
int a,b;
sscanf(os,"%d//%d",a,b);

参考

于 2013-04-26T18:55:43.950 回答
0

看一下strtok函数

于 2013-04-26T18:23:24.050 回答
0

将整数作为字符串。然后字符串将包含数字和 // 符号。接下来,您可以运行一个简单的 for 循环来查找字符串中的“/”。符号之前的值存储在另一个字符串中。当 '/' 出现时,for 循环将终止。您现在有了第一个“/”符号的索引。增加索引并使用另一个 for 循环在另一个字符串中复制字符串的其余部分。现在你有两个单独的字符串。

于 2013-04-26T19:04:01.847 回答
0

这应该拆分并转换为整数:

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

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};

inline double convertToInt(std::string const& s,
                              bool failIfLeftoverChars = true)
{
  std::istringstream i(s);
  int x;
  char c;
  if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
    throw BadConversion("convertToInt(\"" + s + "\")");
  return x;
}

int main()
{
    std::string pieces = "12344//1238";

    unsigned pos;
    pos = pieces.find("//");
    std::string first = pieces.substr(0, pos);
    std::string second = pieces.substr(pos + 2);
    std::cout << "first: " << first << " second " << second << std::endl;
    double d1 = convertToInt(first), d2 = convertToInt(second) ;
    std::cout << d1 << " " << d2 << std::endl ;
}
于 2013-04-26T18:24:06.247 回答
0

我能想到的最简单的方法:

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

using namespace std;

void main ()
{
 int int1, int2;
 char slash1, slash2;

 //HERE IT IS:
 stringstream os ("12344//1238");
 os>> int1 >> slash1 >> slash2 >> int2;
 //You may want to verify that slash1 and slash2 really are /'s

 cout << "I just read in " << int1 << " and " << int2 << ".\n";

 system ("pause");
}

也很好,因为它很容易重写——比如说,如果你决定读入由其他东西分隔的整数。

于 2013-04-26T18:34:07.270 回答