亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用C ++中的ifstream逐行讀取文件

使用C ++中的ifstream逐行讀取文件

紫衣仙女 2019-05-25 15:20:44
使用C ++中的ifstream逐行讀取文件file.txt的內容是:5 36 47 110 511 612 312 45 3坐標對在哪里。如何在C ++中逐行處理此數據?我能夠得到第一行,但是如何獲得文件的下一行?ifstream myfile;myfile.open ("text.txt");
查看完整描述

4 回答

?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

由于你的坐標是成對的,為什么不為它們寫一個結構?

struct CoordinatePair{
    int x;
    int y;};

然后你可以為istreams編寫一個重載的提取運算符:

std::istream& operator>>(std::istream& is, CoordinatePair& coordinates){
    is >> coordinates.x >> coordinates.y;

    return is;}

然后你可以直接將坐標文件讀入這樣的矢量:

#include <fstream>#include <iterator>#include <vector>int main(){
    char filename[] = "coordinates.txt";
    std::vector<CoordinatePair> v;
    std::ifstream ifs(filename);
    if (ifs) {
        std::copy(std::istream_iterator<CoordinatePair>(ifs), 
                std::istream_iterator<CoordinatePair>(),
                std::back_inserter(v));
    }
    else {
        std::cerr << "Couldn't open " << filename << " for reading\n";
    }
    // Now you can work with the contents of v}


查看完整回答
反對 回復 2019-05-25
  • 4 回答
  • 0 關注
  • 4095 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號