G++打印了不需要的00000,为什么?

g++ printed undesired 00000, why?

本文关键字:为什么 00000 打印 不需要 G++      更新时间:2023-10-16

下面是我的代码;

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上进行测试,但我已经为此浪费了太多时间。只要知道你的代码没有错

将来,试着弄清楚你的编码问题是什么。如果您真的尝试过并且无法找出解决方案,那么堆栈溢出是非常宽容的,但您需要展示您尝试过的内容以及结果。对于像这样开始的问题,你认为你正在试图找出一个算法问题,总是给出数据集和发生的意外结果。

祝你好运!