首先,它是一個壞主意用C I/O系統中的C++。使用C++函數std::getline
或類std::basic_istream
的成員函數getline
和/或get
會更好。
考慮到C函數fgets
還在字符串中存儲新行字符。你應該刪除它。例如
while (std::fgets(buff, sizeof buff, fp) != NULL)
{
size_t n = std::strlen(buff);
if (n && buff[n-1] == '\n') buff[n-1] = '\0';
if (buff[0] != '\0') vrecords.push_back(buff);
}
如果載體聲明如下std::vector<std::string>
(我希望它沒有聲明,例如std::vector<char *>
),那麼你可以寫,而不是
std::string record;
while (std::getline(YourFileStream, record))
{
if (!record.empty()) vrecords.push_back(record);
}
在這種情況下找到單詞「買入」是簡單地使用標題<algorithm>
中聲明的標準算法std::find
。例如
#include <algorithm>
#include <iterator>
//...
auto it = std::find(vrecords.begin(), vrecords.end(), "Buy");
if (it != vrecords.end())
{
std::cout << "Word \"" << "Buy"
<< "\" is found at position "
<< std::distance(vrecords.begin(), it)
<< std::endl;
}
如果你需要找到以下任何話買或賣,那麼你可以使用標準算法std::find_first_of
。例如
#include <algorithm>
#include <iterator>
//...
const char * s[] = { "Buy", "Sell" };
auto it = std::find_first_of(vrecords.begin(), vrecords.end(),
std::begin(s), std::end(s));
if (it != vrecords.end())
{
std::cout << "One of the words \"" << "Buy and Sell"
<< "\" is found at position "
<< std::distance(vrecords.begin(), it)
<< std::endl;
}
如果需要計數有多少在向量這樣的話則可以使用上述aproaches在一個循環或使用標準算法std::count
,std::count_if
,std::accumulate
或基於for循環的範圍內。 例如
const char * s[] = { "Buy", "Sell" };
auto n = std::count_if(vrecords.begin(), vrecords.end(),
[&](const std::string &record)
{
return record == s[0] || record == s[1];
});
'if(vrecords [2] ==「Buy」|| vrecords [2] ==「Sell」)'?正則表達式在這裏會過度imo .. – quantdev 2014-11-22 09:04:04
@bro顯示矢量是如何定義的。 – 2014-11-22 09:08:16
vector vrecords; –
bro
2014-11-22 09:11:50