G++打印了不需要的00000,为什么?
g++ printed undesired 00000, why?
下面是我的代码;
int main(){
ifstream infile;
infile.open(fin);
ofstream outfile;
outfile.open(fout);
char c;
int input_order = 0;
string comp_str = "";
vector <string> pfx_str;
srand(time(NULL));
if (infile.fail())
{
cout << "cannot open file!" << endl;
return 0;
}
while (!infile.fail())
{
cout << input_order << endl;
c = infile.get();
if (c == 'n')
{
if (strcmp(comp_str.c_str(), "") != 0)
{
pfx_str.push_back(comp_str);
}
int num = rand() % pfx_str.size();
while (num == 0)
{
num = rand() % pfx_str.size();
}
for (int i = 0; i < num; i++)
{
outfile << "/" << pfx_str.at(i);
}
outfile << "n";
input_order++;
pfx_str.clear();
}
else if (c == '/')
{
if (comp_str != "")
{
pfx_str.push_back(comp_str);
}
comp_str = "";
}
else
{
comp_str = comp_str + c;
}
}
infile.close();
outfile.close();
return 0;
}
对于由 10k 输入组成的小型集,它可以工作。 但是,对于使用 1600k 输入等大集,它会打印出 00000,并且不起作用。是什么让它发生?以及如何使其正常工作? (以前,我将此代码用于 1600k 输入,并且可以正常工作...... 在编译中,我使用了g++ -std=gnu++0x ....
. 我用谷歌搜索了这个问题,但找不到正确的答案。而且我也无法弄清楚这个问题来自什么......
谢谢
+ 此代码用于随机剪切输入。
这是 1 个输入集的示例;(显示输入模式)/aa/ab/bc/aaa/在这里,我认为"aa","ab","bc"和"aaa"是一个组成部分。 我想随机剪切这个输入作为组件单元。 这是代码的简短步骤; 1. 生成随机数(0除外) 2. 例如)我使用上面的输入,随机数是2。 然后我剪切了这个输入,只剩下"2"个组件,即/aa/ab/(对输入文本文件中的每个输入重复此过程
=> 此输入;/aa/ab/bc/aaa/ (在里面,它生成随机数 2) 输出要打印在输出文件中;/aa/ab/
你的代码没有错。
我更新了您的代码,以便它使用 g++ 编译:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(){
ifstream infile;
infile.open("fin.txt"); // substituted a real file name in here to test
ofstream outfile;
outfile.open("fout.txt"); // ditto here
。其余的与您上面放置的相同。
将其命名为test.cpp,并用以下内容进行编译:
g++ -lm test.cpp -o test.exe
我编写了一个 Ruby 脚本,根据您在注释中指定的测试集制作输入文件:
#!/usr/bin/env ruby
File.open( 'fin.txt', 'w') do |f|
1600000.times do
f << "/aa/ab/bc/aaa/n"
end
end
然后我运行了编译的程序测试.exe,你完全欠我一杯啤酒,因为你看着你的行号变得那么高。这是我一生中为你度过的时间,我永远不会回来。
并得到了预期的失败.txt
/aa
/aa/ab
/aa
/aa/ab
/aa/ab/bc
/aa/ab/bc
/aa/ab
/aa/ab/bc
/aa/ab
等。
我的猜测是您的系统约束导致了系统故障。我在具有大量内存等的典型台式机上运行了它。如果您在嵌入式系统上运行它,它可能没有类似的资源。在这一点上,我很想在Raspberry Pi上进行测试,但我已经为此浪费了太多时间。只要知道你的代码没有错。
将来,试着弄清楚你的编码问题是什么。如果您真的尝试过并且无法找出解决方案,那么堆栈溢出是非常宽容的,但您需要展示您尝试过的内容以及结果。对于像这样开始的问题,你认为你正在试图找出一个算法问题,总是给出数据集和发生的意外结果。
祝你好运!
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么比较运算符如此快速
- 为什么 Serial.println(<char[]>);返回随机字符?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 为什么不;名字在地图上是按顺序排列的吗
- 我的字符计数代码计算错误.为什么
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 为什么野牛仍在使用"int yylex(void)",却找不到"int yylex(YYS
- 为什么 std::unique 不调用 std::sort?
- 既然存在危险,为什么项目要使用-I include开关
- G++打印了不需要的00000,为什么?