2013-04-26 58 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循環複製字符串的其餘部分。 現在你有兩個單獨的字符串。