2013-04-26 120 views
0

我有问题总是像这样分割字符串使用拆分使用纯C++</p> <p>的字符串的字符串C++

12344//1238 

一整数,那么//然后第二INT。

需要帮助,以获得两个int值而忽略//

+0

有什么问题?您可能需要查看右侧的第一个相关链接。 – chris 2013-04-26 18:21:57

+0

我不知道如何拆分字符串来获得两个int并忽略// – glethien 2013-04-26 18:22:27

+0

你想用字符串做什么?任何代码? – 2013-04-26 18:22:57

回答

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; 
+0

似乎最好将分隔符定义为一个字符串。然后执行'p + sep.size()'而不是(脆)'p + 2'。 – Madbreaks 2013-04-26 18:28:33

+0

非常感谢!它做了诡计!!!! – glethien 2013-04-26 18:29:14

+0

@Madbreaks我这样做是因为OP表示字符串总是以这种格式。只是为了保持简单。 – stardust 2013-04-26 18:31:22

0

strtok功能

+0

我不介意downvoted,但请说出为什么 – Madbreaks 2013-04-26 18:24:16

+0

它可能比C++更C,并且可能不是线程安全的,但它会*拆分字符串。 – chris 2013-04-26 18:26:06

+0

谢谢@chris,我同意更多的标准C.但是由于C++是C的超集,所以使用它是完全合法的。 – Madbreaks 2013-04-26 18:27:18

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 ; 
} 
+0

这是什么? – Madbreaks 2013-04-26 18:29:37

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"); 
} 

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

1

为什么我们不能使用sscanf?

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

Reference

0

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