【发布时间】:2014-11-08 02:09:16
【问题描述】:
这可能是一个非常简单的问题,但我没有找到任何示例来指导我。我正在尝试用 C++ 编写可以读取文本文件的类,其中数据列(float、char、int 等)由空格分隔。我希望班级能够忽略某些列并读取指定的列。现在我正在试验一列和两列格式并从那里取得进展。下面列出了一个测试输入文件的简短示例。
103.816
43.984
2214.5
321.5
615.8
8.186
37.6
我第一次尝试编写读取一列数据的代码很简单,看起来像这样。
void Read_Columnar_File::Read_File(const std::string& file_name)
{
int i;
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
if(inp.is_open()) {
std::istream_iterator<float> start((inp)), end;
std::vector<float> values(start,end);
for(i=0; i < 7; i++) std::cout << values[i] << std::endl;
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}
在我的下一次尝试中,我尝试仅读取两列格式中的一列,如下所示的输入。这些数字只是为了这个例子而编造的
103.816 34.18
43.984 21.564
2214.5 18.5
321.5 1.00
615.8 4.28
8.186 1.69
37.6 35.48
我稍微修改了代码格式,使其看起来像下面的示例。我在 inp >> 语句之后使用了一个简短但伪代码来说明我试图让代码在阅读第一列后跳到下一行。我的问题是“我如何让代码只读取第一列,然后跳到下一行,它再次读取第一列数据并让它继续这样做直到文件结束?”并提前感谢您提供的任何建议。
void Read_Columnar_File::Read_File(const std::string& file_name)
{
int i;
float input;
std::vector<float> values;
std::ifstream inp(file_name,std::ios::in | std::ios::binary);
if(inp.is_open()) {
for(i=0; i < 7; i++) {
inp >> input >> \\ - At this point I want the code to skip to the next
\\ line of the input file to only read the first column
\\ of data
values.push_back(input);
}
for(i=0; i < 7; i++) std::cout << values[i] << std::endl;
}
else std::cout << "Cannot Open " << file_name << std::endl;
inp.close();
}
【问题讨论】: