我知道在SO(和其他地方)已经讨论了很多 . 因为我还在被困,所以我在这里求助 . 也许我正在做一些真正无脑/愚蠢的事情,或者这可能是真正的问题......
我有一个文件目录,每个都有扩展名'.pts' - 打开一个显示:
版本:1 n_points:68 {498.801220 504.771171 516.076459 571.681686 518.038170 628.516761 ...
粘贴在这里得到格式错误一点,所以请注意每行数据之间没有空行 . 这些浮子对中也有68个,但我在这里省略了它们 .
最终我想要一对对齐的矢量作为圆形短裤 - 例如499,505,516,572,518,629 ......
但目前我无法按原样访问花车,更不用说任何信息了 .
到目前为止的代码:
#include <iostream>
#include <string>
#include "dirent.h"
#include <fstream>
#include <sstream>
#include <stdio.h>
using namespace std;
bool has_suffix(const string& s, const string& suffix)
{
return (s.size() >= suffix.size()) && equal(suffix.rbegin(), suffix.rend(), s.rbegin());
}
int main(int argc, char **argv)
{
string path = "C:\\testset";
DIR *dir = opendir(path.c_str());
if(!dir)
{
return 1;
}
dirent *entry;
string fileName;
float number;
string dummy;
while(entry = readdir(dir))
{
if(has_suffix(entry->d_name, ".pts"))
{
fileName = entry->d_name;
fileName = path + "\\" + fileName; // <<added at suggestion of Martin James
//Working up to here as I see all the .pts files listed when I print them:
cout << fileName << endl;
ifstream file(fileName, std::ios_base::in);
//however from here:
while (file >> number)
{
//...nothing will print
printf("%f ", number);
}
file.close();
}
}
closedir(dir);
}
查找所有.pts文件正在工作(感谢SO :)上的其他线程 - 并且它们看起来是简单的.text文件,因为它们在文本编辑器中打开 . 每行末尾都有一个'LF' .
问题是运行代码只会导致列出文件名 . 似乎“while(文件>>数字)”没有返回任何内容来运行print语句 . 事情是,主题上的其他主题(至少对我而言)表明它就像这样简单 .
我觉得答案很可能涉及到我在过去几个小时里看过的东西 - 虚拟字符串变量来吸收我不需要的文件顶部的所有东西?函数getline? “代币”?我会告诉你我所有的努力,但我不想陷入这个问题:
Given a txt file formatted like above how would you access the values from line 4 onwards?
任何帮助非常感谢:)
1 回答
这里的问题是,您没有阅读 Headers 信息 .
>>
操作失败,因为您尝试将字符串"version: 1"作为float读入 .要解决此问题,您应该跳过 Headers ,只需调用
std::getline
,或者解析它以获取有关内容的信息 .Edit: 要跳过您可以执行的操作: