file.txt的内容是:
5 3
6 4
7 1
10 5
11 6
12 3
12 4
Run Code Online (Sandbox Code Playgroud)
5 3坐标对在哪里.如何在C++中逐行处理此数据?
我能够得到第一行,但是如何获得文件的下一行?
ifstream myfile;
myfile.open ("text.txt");
Run Code Online (Sandbox Code Playgroud) 我刚刚在这个答案中发现了一条评论说iostream::eof在循环条件下使用"几乎肯定是错误的".我通常使用类似的东西while(cin>>n)- 我猜是隐式检查EOF,为什么检查eof显式使用while (!cin.eof())错误?
它与scanf("...",...)!=EOF在C中使用有何不同(我经常使用没有问题)?
我正在尝试使用time()来衡量我的程序的各个点.
我不明白为什么之前和之后的值是一样的?我知道这不是描述我的程序的最佳方式,我只想看看有多长时间.
printf("**MyProgram::before time= %ld\n", time(NULL));
doSomthing();
doSomthingLong();
printf("**MyProgram::after time= %ld\n", time(NULL));
Run Code Online (Sandbox Code Playgroud)
我试过了:
struct timeval diff, startTV, endTV;
gettimeofday(&startTV, NULL);
doSomething();
doSomethingLong();
gettimeofday(&endTV, NULL);
timersub(&endTV, &startTV, &diff);
printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);
Run Code Online (Sandbox Code Playgroud)
我如何阅读结果**time taken = 0 26339?这是否意味着26,339纳秒= 26.3毫秒?
那怎么说**time taken = 4 45025,这意味着4秒和25毫秒?
我有一个包含数百万行的文件,每行有3个以空格分隔的浮点数.读取文件需要花费大量时间,因此我尝试使用内存映射文件读取它们,但发现问题不在于IO的速度,而在于解析速度.
我当前的解析是获取流(称为文件)并执行以下操作
float x,y,z;
file >> x >> y >> z;
Run Code Online (Sandbox Code Playgroud)
Stack Overflow中的某些人建议使用Boost.Spirit,但我找不到任何简单的教程来解释如何使用它.
我正在尝试找到一种简单有效的方法来解析看起来像这样的行:
"134.32 3545.87 3425"
Run Code Online (Sandbox Code Playgroud)
我真的很感激一些帮助.我想用strtok来分割它,但我不知道如何将字符串转换为浮点数,我不太确定它是最好的方法.
我不介意解决方案是否会提升.我不介意它是不是有史以来最有效的解决方案,但我确信它可以加倍速度.
提前致谢.
我正在编写一个小程序来处理一个大文本文件并进行一些替换.问题是它永远不会停止分配新的内存,所以最终它会耗尽内存.我已经将它简化为一个简单的程序,只需计算行数(参见下面的代码),同时仍然分配越来越多的内存.我必须承认,我对提升和提升精神知之甚少.你能告诉我我做错了什么吗?太感谢了!
#include <string>
#include <iostream>
#include <boost/spirit/include/lex_lexertl.hpp>
#include <boost/bind.hpp>
#include <boost/ref.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
// Token ids
enum token_ids {
ID_EOL= 100
};
// Token definition
template <typename Lexer>
struct var_replace_tokens : boost::spirit::lex::lexer<Lexer> {
var_replace_tokens() {
this->self.add ("\n", ID_EOL); // newline characters
}
};
// Functor
struct replacer {
typedef bool result_type;
template <typename Token>
bool operator()(Token const& t, std::size_t& lines) const {
switch (t.id()) {
case ID_EOL:
lines++;
break;
}
return true;
}
};
int main(int argc, char **argv) { …Run Code Online (Sandbox Code Playgroud) c++ ×5
boost-spirit ×2
boost ×1
c ×1
c++-faq ×1
file-io ×1
iostream ×1
linux ×1
measurement ×1
memory-leaks ×1
ofstream ×1
parsing ×1
time ×1