首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从文件读取输入

从文件读取输入
EN

Stack Overflow用户
提问于 2012-10-18 13:12:17
回答 2查看 77关注 0票数 1

list.txt

代码语言:javascript
复制
first 10
second third 20
fourth fifth 30
.
.
.

把第一行和其他行分开阅读的常规方法是什么,这样我就可以用" first ","second",……还有10,20,...在程序中的其他地方作为它们各自的类型?

谢谢!

EN

Stack Overflow用户

发布于 2012-10-18 13:21:42

代码语言:javascript
复制
struct header { 
    std::string name;
    int number;
};

std::istream &operator>>(std::istream &is, header &h) { 
    return is >> h.name >> h.number;
}

struct line { 
    std::string first;
    std::string second;
    int number;
};

std::istream &operator>>(std::istream &is, line &data) { 
    returns is >> data.first >> data.second >> data.number;
}

int main() { 
    header h;
    std::ifstream data("list.txt");

   // read first line:
   data >> h;
   // now h.name and h.number are the string and number from the first line

   // read the rest of the lines:
   std::vector<line> lines((std::istream_iterator<line>(data),
                            std::istream_iterator<line>());

   // now lines[i].first, lines[i].second and lines[i].number
   // are the first string, second string, and number
   // from the i-th line of three-field data from the file.

   return 0;
}
票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12947541

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档