[英]What is the best way to store data from text file into C++ in order to Edit
[英]Reading from a text file, best way to store data C++
基本上我有一个文本文件,我需要读入值,以便程序可以操作它们。
我使用C ++,我已经编写了工作代码来判断文件是否存在。
文本文件的格式如下:
1 7
8 10
20 6
3 14
...
左边的值是X值,右边的值是Y值。 (中间的空格是一个选项卡)如何提取此数据? 说把它们传递给像这样的班级......
myVector(X,Y);
另外,我想在我可以在类中使用它之前我必须将TryParse从字符串更改为int对吗? C ++可以这样做吗?
谢谢!
如果我是你,我会写这样的东西。 注意,这只是原型代码,甚至没有经过测试。
基本思想是在一行中读取两次,但使用不同的分隔符。 您将首先使用制表符分隔符进行读取,然后仅使用默认行结束。
当你没有更多要阅读的内容时,你需要确保优雅地退出循环,因此如果你的文件是“正确的”,那么第二个就足够了。
您还需要确保转换为矢量类所需的正确类型。 我假设这是int,但如果它是字符串,则不需要我已经实现的转换。
#include <string>
#include <fstream>
using namespace std;
void yourFunction()
{
..
ifstream myfile("myfile.txt");
string xword, yword;
while (1) {
if (!getline(myfile, xword, '\t'))
break;
if (!getline(myfile, yword))
break;
myVector.push_back(stoi(xword), stoi(yword));
}
...
}
这种解析可以使用boost.spirit在一行中完成:
qi::phrase_parse(begin, end, *(qi::int_ > qi::int_ > qi::eol), qi::ascii::blank, v);
语法可以读作:“读取一个int,然后一个int,然后一个EOL(行尾)(\\ n或\\ r \\ n,取决于语言环境),尽可能多的时间”。 在int和EOL之间可以找到空白字符(例如空格或制表符)。
优点:而不是std :: getline循环,代码更清晰/简洁。 spirit.qi让你更强大的控制,你不需要stoi电话。 缺点:构建 - 依赖(不依赖)spirit.qi,编译时间。
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/include/std_pair.hpp>
namespace spirit = boost::spirit;
namespace qi = spirit::qi;
int main(int argc, char **argv)
{
std::ifstream in(argv[1], std::ios_base::in);
std::string storage;
in.unsetf(std::ios::skipws);
spirit::istream_iterator begin(in), end;
std::vector<std::pair<int, int> > v;
qi::phrase_parse(begin, end, *(qi::int_ > qi::int_ > qi::eol), qi::ascii::blank, v);
for(const auto& p : v)
std::cout << p.first << "," << p.second << std::endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.