【发布时间】:2015-04-02 15:00:00
【问题描述】:
我是使用 C++ 和 Microsoft Visual Studio 的新手,我尝试将数据文件(2 列 x 500 行,由浮点数组成)转换为数组,然后尝试在屏幕上输出数组。每当我尝试运行它时,它都会出现“file.exe 中 0x001BC864 处的未处理异常:0xC0000005:访问冲突写入位置 0x00320A20。”
我找到了这个视频并尝试修改该代码https://www.youtube.com/watch?v=4nz6rPzVm70
任何帮助将不胜感激。
#include<stdio.h>
#include<string>
#include<iostream> //
#include<fstream> //
#include<array> //
#include<iomanip> //
#include<sstream>//
#include<conio.h>
using namespace std;
int rowA = 0; //
int colA = 0;
int main()
{
string lineA;
int x;
float arrayA[2][500] = { { 0 } };
ifstream myfile("C:/results.dat");
if (myfile.fail()) {
cerr << "File you are trying to access cannot be found or opened";
exit(1);
}
while (myfile.good()) {
while (getline(myfile, lineA)) {
istringstream streamA(lineA);
colA = 0;
while (streamA >> x) {
arrayA[rowA][colA] = x;
colA++; }
rowA++; }
}
cout << "# of Rows --->" << rowA << endl;
cout << "# of Columns --->" << colA << endl;
cout << " " << endl;
for (int i = 0; i < rowA; i++) {
for (int j = 0; j < colA; j++) {
cout << left << setw(6) << arrayA[i][j] << " ";
}
cout << endl;
}
return 0;
_getch();
}
【问题讨论】:
-
如果你有 500 行,每行两个浮点数,那么
float arrayA[2][500]和arrayA[rowA][colA]不能很好地结合在一起。如果你有 2 行 500 个浮点数,他们会这样做。 -
好的,谢谢,请问您有什么建议吗?
-
这个问题不是 Visual Studio 特有的。这是一个通用的 C++ 问题。您在使用 c++ 数组时遇到问题就是问题所在。掌握编程的第一步是能够确定问题的根源。
-
尝试 [here][1] for floats 或 [here][2] for ints [1]: stackoverflow.com/questions/8421170/read-floats-from-a-txt-file [2]: stackoverflow.com/questions/8116808/…
-
float arrayA[500][2]可能会解决此特定文件的问题。更一般地,看一下std::vector,其中元素的数量不必在编译时知道(并且可以在运行时调整),并且知道你可以有一个std::vector<std::vector<float>>。在不了解您正在阅读的数据的含义和结构的情况下,我可以提供尽可能多的建议。
标签: c++ visual-studio