2014-04-28 216 views
2

我已經使用數字和字符填充了一個字符串向量(*,+,-,/)。我想將每個數字和字符分配給兩個新的矢量,以及矢量和一個char矢量。有沒有辦法將字符串轉換爲所需的數據類型?將字符串轉換爲char和int數據類型

回答

2

您可以在<sstream>頭使用字符串流。

string myString = "123"; 
stringstream sStream(myString); 
int convertedInt; 
sStream >> convertedInt. 
0

附上<sstream>頭,你可以做這樣的事情:

std::vector<std::string> stringVector = /* get data from somewhere */ 

std::vector<int> intVector; 
std::vector<char> charVector; 

for (std::vector<std::string>::const_iterator it = stringVector.begin(); it != stringVector.end(); it++) 
{ 
    if (it->length() == 0) 
     continue; // ignore any empty strings 

    int intValue; 
    std::istingstream ss(*it); 
    if (ss >> someValue) // try to parse string as integer 
     intVector.push_back(someValue); // int parsed successfully 
    else 
     charVector.pushBack((*it)[0]); 
} 

這是假設任何一個整數應推入焦炭載體,而不是(這樣,234100000無法解析和-34將投入intVector/+等將投入charVector)。只有非整數值的第一個字符推,所以如果你有*hello*123,只有*將投入的charVector

如果您使用的是C++ 11,則可以將std::vector<std::string>::const_iteratorauto對換,使其看起來更漂亮一些。

相關問題