这可能是一个非常简单的问题,但我还没有找到任何例子来指导我。我正在尝试用 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();
}
最佳答案
你可以使用成员函数ignore()
来丢弃直到下一行的所有字符。我还会修复您的代码,以使用基于提取成功的 for()
循环,以便您的代码适用于任意数量的列,而不仅仅是 7:
for (float input; inp >> input; values.push_back(input))
{
inp.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
关于c++ - 尝试用 C++ 编写一个只读取第一列数据并跳到下一行的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26812956/