簡體   English   中英

在C ++中從文本文件讀取時如何跳過特定的列?

[英]How to skip specific column while reading from text file in C++?

我有一個三列的文本文件。 我只想閱讀第一個和第三個。 第二列由名稱或日期組成。

輸入文件 讀取數據

7.1 2000-01-01 3.4 | 7.1 3.4

1.2 2000-01-02 2.5 | 1.2 2.5

要么

5.5未知3.9 | 5.5 3.9

1.1未知2.4 | 1.1 2.4

有人可以提示我如何在C ++中執行此操作嗎?

謝謝!

“有人可以提示我如何在C ++中做到這一點嗎?”

當然可以:

  1. 使用std::getline逐行瀏覽文件,將每一行讀入std::string line;
  2. 為每一行構造一個臨時的std::istringstream對象
  3. 在此流上使用>>運算符來填充double類型的變量(第一列)
  4. 再次使用>>將您實際上不會使用的第二列讀入std::string
  5. 使用>>讀取另一double (第3列)

即類似:

std::ifstream file;
...
std::string line;
while (std::getline(file, line)) {
    if (line.empty()) continue;     // skips empty lines
    std::istringstream is(line);    // construct temporary istringstream
    double col1, col3;
    std::string col2;
    if (is >> col1 >> col2 >> col3) {
        std::cout << "column 1: " << col1 << " column 3: " << col3 << std::endl;
    }
    else {
        std::cout << "This line didn't meet the expected format." << std::endl;
    }
}

有人可以提示我如何在C ++中執行此操作嗎?

只需使用std::basic_istream::operator>>將跳過的數據放入虛擬變量,或使用std::basic_istream::ignore()跳過輸入,直到您指定的下一個字段定界符為止。

最好的解決方法是使用std::ifstream逐行讀取(請參閱std::string::getline() ),然后使用std::istringstream分別解析(並跳過上述列)每行循環遍歷輸入文件中的所有行。

問題解決如下:

int main()
{   
ifstream file("lixo2.txt");
string line; int nl=0; int nc = 0; double temp=0;

vector<vector<double> > matrix;

while (getline(file, line))
{
size_t found = line.find("Unknown");
line.erase (found, 7);
istringstream is(line);

vector<double> myvector;

while(is >> temp)
{
    myvector.push_back(temp);
    nc = nc+1;
}
matrix.push_back(myvector);

 nl =nl+1;
}

return 0;
}

謝謝大家!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM