[英]C++ int and string parsing with delimiters
我試圖找到一種方法來分割字符串來查找數字和特定的單詞。 在這里,我試圖讀取蘋果和橘子的數量。 但是,我寫這個的方式,如果單詞“apple”或“orange”之前或之后是標點符號,它將不計算在內。 例如,考慮文本文件:
3個蘋果2個橘子
3個蘋果。 2個橘子。
(3個蘋果2個橙子)
由於沒有任何標點符號,此程序將僅計算第一行。 我希望有人能告訴我更好的解決這個問題的方法。
#include <iostream>
#include <string>
#include <fstream>
#include<sstream>
using namespace std;
void readString(string line, int& a, int& o);
//splits the string up into substrings
void assignValue(string str, int& a, int& o, int v);
// takes the word following the value and decides whether to assign it to apples, oranges, or neither
int main()
{
ifstream inStream;
inStream.open(name_of_file);
int apples = 0, oranges = 0;
string line;
while (!(inStream.eof()))
{
getline(inStream, line);
readString(line, apples, oranges);
}
cout << "Apples:" << apples << endl;
cout << "Oranges" << oranges << endl;
inStream.close();
system("pause");
return 0;
}
void readString(string l, int& a, int& o)
{
stringstream ss(l);
string word;
int value = 0;
while (ss >> word)
{
istringstream convert(word
if (convert >> value)
{
ss >> word;
assignValue(word, a, o, value);
}
}
}
void assignValue(string str, int& a, int& o, int v)
{
if (str == "apples")
{
a += v;
}
if (str == "oranges")
{
o += v;
}
}
在我看來,這里所需要的就是在執行現有的解析代碼之前將字符串中的任何標點符號替換為空格,這樣就可以很好地將字符串切換成以空格分隔的單詞。
我們將“標點符號”定義為“除字母或數字之外的任何內容”。
您可以在構造其std::stringstream
之前在readString()
使用std::replace_if
():
std::replace_if(l.begin(), l.end(), [](char c) { return !isalnum(c) }, ' ');
或者,如果你想有點明確:
for (char &c:l)
{
if (!isalnum(c))
c=' ';
}
現在,所有標點符號現在都被空格替換,現有的代碼在此之后應該很好地清理。
如果您的數值可能是小數,則可能出現的復雜情況。 由於您將它們聲明為int
,因此情況並非如此。 但是,如果你必須接受類似“4.5蘋果”之類的東西作為輸入,那么這將需要額外的工作,因為這段代碼將很樂意用空格替換句號。 但是,這只是一個心理記錄,要記住。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.