[英]Save next word, if a given word is found (C++)
我是C ++的新手。 我有一個看起來像這樣的文本文檔:
InputFile.txt
...
.
..
.
.
....
TIME/DISTANCE = 500/ 0.1500E+05
..
..
.
...
TIME/DISTANCE = 500/ 1.5400E+02
.
...
...
.
TIME/DISTANCE = 500/ 320.0565
..
..
.
.
...
顯示的一行在整個文件中不斷重復。 我的目標是將500/
之后的所有數字保存到數組/向量/另一個文件/任何內容中。 我知道如何讀取文件並獲取一行:
string line;
vector <string> v1;
ifstream txtfile ("InputFile.txt");
if (txtfile.is_open())
{
while (txtfile.good())
{
while( getline( txtfile, line ) )
{
// ?????
// if(line.find("500/") != string::npos)
// ?????
}
}
txtfile.close();
}
有人有解決方案嗎? 還是指出我正確的方向?
提前致謝。
編輯:兩個提議的解決方案(傑里和加利克)都完美地運作。 我喜歡這個社區。 :)
這是(IMO)在C ++中使用sscanf
可能有意義的極少數情況之一。
std::string line;
std::vector<double> numbers;
while (std::getline(txtfile, line)) {
double d;
if (1==sscanf(line.c_str(), " TIME/DISTANCE = 500 / %lf", &d))
numbers.push_back(d);
}
這會占用每一行,並嘗試將其視為具有您關注的格式。 如果成功, sscanf
的返回值將為1(轉換的項目數)。 如果失敗,返回值將為0(即,它沒有成功轉換任何內容)。 然后我們保存它,如果(並且只有)成功轉換。
另請注意, sscanf
足夠“智能”,可以將格式字符串中的單個空格視為與輸入中任意數量的空白區域相匹配,因此我們不必嘗試精確匹配空白區域。
我們可以稍微改變一下。 如果在'/'之前必須有一個數字,但它可能與500
不同,我們可以用%*d
替換格式字符串的那部分。 這意味着sscanf
將在那里搜索一個數字(特別是整數),但不會將其分配給任何東西。 如果它找到的不是整數,轉換將失敗,因此(例如) TIME/DISTANCE ABC/1.234
將失敗,但TIME/DISTANCE 234/1.l234
將成功。
在處理您的行時,您可以使用line.find()
檢查其右側行並查找您的數據:
if(line.find("TIME/DISTANCE") != std::string::npos)
{
// this is the correct line
}
獲得正確的行后,您可以獲得數據的位置,如下所示:
std::string::size_type pos = line.find("500/");
if(pos != std::string::npos)
{
// pos holds the position of the numbers you want
std::string wanted_numbers = lint.substr(pos + 4); // get only the numbers in a string
}
希望有所幫助
編輯:修正了錯誤(添加4到pos跳過“500 /”部分)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.