2016-02-12 75 views
-1

我剛開始學習C++,我在想他們是任何拆分字符串的方式。讓我們更清楚。 假設用戶輸入字符串,出生日期格式爲dd-mm-yy。現在我希望將日期,月份和年份存儲在3個不同的變量中。那麼我該如何去?
P.S:我google了一下,發現這可以使用boot::regex完成。但是,我仍然想知道是否有更簡單的方法來做同樣的事情。成爲初學者會阻礙我。 :P 反正,任何幫助,將不勝感激。
簡要說明:
我想要類似這樣的東西。將字符串拆分爲C++中的部分

Enter date: //Accept the date 
22-3-17  //Input by user 
Date : 22 //Output 
Month: 3 //Output 
Year : 17 //Output 

回答

1

你可以使用sscanf函數: http://en.cppreference.com/w/cpp/io/c/fscanf

#include <iostream> 
#include <string> 
using namespace std; 

int main(int argc, const char * argv[]) { 
    string date; 
    cin>>date; 
    int day, month, year; 
    sscanf(date.c_str(), "%d-%d-%d", &day, &month, &year); 
    cout << day << ' ' << month << ' ' << year; 
    return 0; 
} 
0

下面是已經編譯,建成併成功一個完整的工作程序運行上的英特爾酷睿2四核至尊運行Windows 7 64位使用Visual Studio已檢索到的信息OP 2015年社區版以特定格式要求,適當地解析了一系列信息或數據,並以請求或要求的格式顯示結果。

stdafx.h中

#ifndef STDAFX_H 
#define STDAFX_H 

#include <vector> 
#include <algorithm> 
#include <iterator> 

#include <tchar.h> 
#include <conio.h> 

#include <string> 
#include <iostream> 
#include <iomanip> 

enum ReturnCode { 
    RETURN_OK = 0, 
    RETURN_ERROR = 1, 
}; // ReturnCode 

#endif // STDAFX_H 

stdafx.cpp

#include "stdafx.h" 

Utility.h

#ifndef UTILITY_H 
#define UTILITY_H 

class Utility { 
public: 

    static void pressAnyKeyToQuit(); 

    static std::string toUpper(const std::string& str); 
    static std::string toLower(const std::string& str); 
    static std::string trim(const std::string& str, const std::string elementsToTrim = " \t\n\r"); 

    static unsigned  convertToUnsigned(const std::string& str); 
    static int   convertToInt(const std::string& str); 
    static float  convertToFloat(const std::string& str); 

    static std::vector<std::string> splitString(const std::string& strStringToSplit, const std::string& strDelimiter, const bool keepEmpty = true); 

private: 
    Utility(); // Private - Not A Class Object 
    Utility(const Utility& c); // Not Implemented 
    Utility& operator=(const Utility& c); // Not Implemented 

    template<typename T> 
    static bool stringToValue(const std::string& str, T* pValue, unsigned uNumValues); 

    template<typename T> 
    static T getValue(const std::string& str, std::size_t& remainder); 

}; // Utility 

#include "Utility.inl" 

#endif // UTILITY_H 

Utility.inl

// ---------------------------------------------------------------------------- 
// stringToValue() 
template<typename T> 
static bool Utility::stringToValue(const std::string& str, T* pValue, unsigned uNumValues) { 
    int numCommas = std::count(str.begin(), str.end(), ','); 
    if (numCommas != uNumValues - 1) { 
     return false; 
    } 

    std::size_t remainder; 
    pValue[0] = getValue<T>(str, remainder); 

    if (uNumValues == 1) { 
     if (str.size() != remainder) { 
      return false; 
     } 
    } 
    else { 
     std::size_t offset = remainder; 
     if (str.at(offset) != ',') { 
      return false; 
     } 

     unsigned uLastIdx = uNumValues - 1; 
     for (unsigned u = 1; u < uNumValues; ++u) { 
      pValue[u] = getValue<T>(str.substr(++offset), remainder); 
      offset += remainder; 
      if ((u < uLastIdx && str.at(offset) != ',') || 
       (u == uLastIdx && offset != str.size())) 
      { 
       return false; 
      } 
     } 
    } 
    return true; 
} // stringToValue 

Utility.cpp

#include "stdafx.h" 
#include "Utility.h" 

// ---------------------------------------------------------------------------- 
// pressAnyKeyToQuit() 
void Utility::pressAnyKeyToQuit() { 
    std::cout << "Press any key to quit" << std::endl; 
    _getch(); 
} // pressAnyKeyToQuit 

// ---------------------------------------------------------------------------- 
// toUpper() 
std::string Utility::toUpper(const std::string& str) { 
    std::string result = str; 
    std::transform(str.begin(), str.end(), result.begin(), ::toupper); 
return result; 
} // toUpper 


// ---------------------------------------------------------------------------- 
// toLower() 
std::string Utility::toLower(const std::string& str) { 
    std::string result = str; 
    std::transform(str.begin(), str.end(), result.begin(), ::tolower); 
    return result; 
} // toLower 

// ---------------------------------------------------------------------------- 
// trim() 
// Removes Elements To Trim From Left And Right Side Of The str 
std::string Utility::trim(const std::string& str, const std::string elementsToTrim) { 
    std::basic_string<char>::size_type firstIndex = str.find_first_not_of(elementsToTrim); 
    if (firstIndex == std::string::npos) { 
     return std::string(); // Nothing Left 
    } 

    std::basic_string<char>::size_type lastIndex = str.find_last_not_of(elementsToTrim); 
    return str.substr(firstIndex, lastIndex - firstIndex + 1); 
} // trim 

// ---------------------------------------------------------------------------- 
// getValue() 
template<> 
float Utility::getValue(const std::string& str, std::size_t& remainder) { 
    return std::stof(str, &remainder); 
} // getValue <float> 

// ---------------------------------------------------------------------------- 
// getValue() 
template<> 
int Utility::getValue(const std::string& str, std::size_t& remainder) { 
    return std::stoi(str, &remainder); 
} // getValue <int> 

// ---------------------------------------------------------------------------- 
// getValue() 
template<> 
unsigned Utility::getValue(const std::string& str, std::size_t& remainder) { 
    return std::stoul(str, &remainder); 
} // getValue <unsigned> 

// ---------------------------------------------------------------------------- 
// convertToUnsigned() 
unsigned Utility::convertToUnsigned(const std::string& str) { 
    unsigned u = 0; 
    if (!stringToValue(str, &u, 1)) { 
     std::ostringstream strStream; 
     strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to unsigned"; 
     throw strStream.str(); 
    } 
    return u; 
} // convertToUnsigned 

// ---------------------------------------------------------------------------- 
// convertToInt() 
int Utility::convertToInt(const std::string& str) { 
    int i = 0; 
    if (!stringToValue(str, &i, 1)) { 
     std::ostringstream strStream; 
     strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to int"; 
     throw strStream.str(); 
    } 
    return i; 
} // convertToInt 

// ---------------------------------------------------------------------------- 
// convertToFloat() 
float Utility::convertToFloat(const std::string& str) { 
    float f = 0; 
    if (!stringToValue(str, &f, 1)) { 
     std::ostringstream strStream; 
     strStream << __FUNCTION__ << " Bad conversion of [" << str << "] to float"; 
     throw strStream.str(); 
    } 
    return f; 
} // convertToFloat 

// ---------------------------------------------------------------------------- 
// splitString() 
std::vector<std::string> Utility::splitString(const std::string& strStringToSplit, const std::string& strDelimiter, const bool keepEmpty) { 
    std::vector<std::string> vResult; 
    if (strDelimiter.empty()) { 
     vResult.push_back(strStringToSplit); 
     return vResult; 
    } 

    std::string::const_iterator itSubStrStart = strStringToSplit.begin(), itSubStrEnd; 
    while (true) { 
     itSubStrEnd = search(itSubStrStart, strStringToSplit.end(), strDelimiter.begin(), strDelimiter.end()); 
     std::string strTemp(itSubStrStart, itSubStrEnd); 
     if (keepEmpty || !strTemp.empty()) { 
      vResult.push_back(strTemp); 
     } 

     if (itSubStrEnd == strStringToSplit.end()) { 
      break; 
     } 

     itSubStrStart = itSubStrEnd + strDelimiter.size(); 
    } 

    return vResult; 

} // splitString 

的main.cpp

#include "stdafx.h" 
#include "Utility.h" 

int main() { 
    std::string date; 
    std::cout << "Enter Date in DD-MM-YY Format.\n" << std::endl; 

    std::getline(std::cin, date); 

    std::vector<std::string> vResults = Utility::splitString(date, "-"); 

    std::cout << "\nDate : " << vResults[0] << std::endl 
       << "Month: " << vResults[1] << std::endl 
       << "Year : " << vResults[2] << std::endl << std::endl;  

    Utility::pressAnyKeyToQuit(); 
    return 0; 
} // main 
+0

此實用工具類可能看起來有點過分,在第一,但它是一個非常方便的類來封裝許多字符串操作函數,人們會反覆使用它。這個類不是「對象」類,這意味着你不能創建一個Utility對象的實例,因爲它的構造函數是私有的。但是,所有方法都是靜態的,因此使用它很簡單。只需在需要的地方包含標題並使用範圍解析運算符。此外,如果您有任何預定義的常量字符串,您可以將它們靜態放置在此類的公共部分中,以保持整潔。 –