[英]C++: follow-up question on reading from an external file using getline(). How to get a subset of the file data?
我需要從外部文件中讀取數字,並將其存儲在整數向量中。 感謝霍華德·辛南特(Howard Hinnant)和威廉·威廉(wilhelmtell),我現在可以做到這一點,他們耐心地幫助弄清了為什么我的編碼昨天不起作用。
我一直在嘗試找出如何在代碼中合並其他功能,但是我已經用盡了對流的知識,希望能得到一些建議。
我希望能夠處理包含許多數據集的文件。 是否可以僅將文件中的某些數據提取到向量中? 我想以幾個向量結尾,這些向量包含來自文件不同部分的數據。 我在網上搜索,但沒有看到任何提及。
這是代碼以及我要從中獲取數據的文件示例(我們稱之為“測試”)。
編輯: 我根據CashCow的建議編輯了代碼。 我現在可以從數據文件中獲取一個塊。 但是我不知道如何獲得我想要的東西。 如果按原樣運行代碼,則會得到一個包含元素2,5,8的向量(這不是我想要的)。 為了獲得vectorTwo(在我的示例中為4、5、6),我嘗試在while語句周圍添加以下內容:
if( line == "vectorTwo" )
{
// The while statement and its contents
}
這沒用。 我從運行代碼(盡管已編譯)沒有得到任何結果。 誰能看到問題所在? 我認為我可以使用此語句搜索所需數據塊的標題。
//這里是示例文件的內容
vectorOne //一個向量的數據子集的標識符
'1''2''3'
vectorTwo //我將如何獲得一個向量? 還是其他任何一個向量?
'4''5''6'
vectorThree //另一個向量的數據子集標識符
'7''8''9'
//代碼:“ \\”字符是行定界符。 直到第一個“”都將被忽略,然后直到下一個“”都將被忽略。 繼續直到邏輯失敗(文件結束)。 如何使它停止在數據塊的末尾?
#include <fstream>
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
int main()
{
std::string line;
std::string block; // Edited, from CashCow
const std::string fileName = "test.dat";
std::ifstream theStream( fileName.c_str() );
if( ! theStream )
std::cerr << "Error opening file test.dat\n";
std::vector<int> numbers; // This code is written for one vector only. There would be three vectors for the example file I provided above; one for the vectorOne data in the file, and so on.
while (true)
{
// get first '
std::getline(theStream, line, '\'');
// read until second '
std::getline(theStream, line, '\'');
std::istringstream myStream( line );
std::getline( theStream, block, '\n' ); // Edited, from CashCow
std::istringstream blockstream( block ); // Edited, from CashCow
std::getline(blockstream, line, '\''); // Edited, from CashCow
int i;
myStream >> i;
if (myStream.fail())
break;
numbers.push_back(i);
}
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"));
}
當到達塊的開頭時,只需將行的末尾讀入字符串中,然后解析該字符串即可。
std::getline( theStream, block, '\n' );
std::istringstream blockStream( block );
std::getline( blockStream, line, '\'' ); // etc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.