文件输入c ++不正确

时间:2013-01-14 23:32:49

标签: c++ file random input

由于某种原因,此代码

for (i = 0; i < 1024; i++)
    mem[i] = 0;

  //Read input file
  instructions.open (fname.c_str(), fstream::in);
  if (!instructions.is_open() ) {
    std::cout << "Error 404: file not found\n";
    exit (404);
  }

for (i = initial_pos; !instructions.eof(); i++) 
  instructions >> mem[i];

正在读取此文件

1
21
1
9
11
9
16
11
9
3
60
2
0
21
0
1
11
4
0
2
2
90
0

因此:

1
33
1
32
11
0
28
11
1
26
11
2
24
11
3
22
41
1
1
51
8
22
1
3
21
2
0
60
34
12
5
2
2
3
90
0
0
0
1
0

&gt;&gt;有什么特别的原因吗?操作数似乎是为mem添加随机数?请注意,mem是一个初始化的数组,所有数字都是在读完后打印出来的。

2 个答案:

答案 0 :(得分:2)

冒着写第一百次的风险,这是你的代码应该

的方式:

std::ifstream infile(fname.c_str());   // "in" is implied

if (!infile) { /* error, could not open file */ }

for (int n; infile >> n; )
{
    // we read the number n
}

如果你只想要一个整数容器,那就更好了:

#include <vector>
#include <iterator>
#include <fstream>

std::ifstream infile(fname.c_str());
std::istream_iterator<int> beg(infile), end();

std::vector<int> v(beg, end);

// now "v" contains all the integers.

答案 1 :(得分:0)

修正了它。我把可执行文件称为错误。

应该是:

[[[[输入名称]]]]

但我这样称呼它:

sim test1.bin

因此模拟器将初始PC设置为“test1.bin”并将输入设置为默认输入“input.bin”,因此我读错了文件。

我想这总是归结为糟糕的家庭作业任务。