[英]Reading in numbers from a file into an array
所以我有一個包含三列的文件,例如:
1 1 750
這些是x,y,強度值。
然后我嘗試將這個長文件讀入數組。 這是到目前為止的代碼:
using std::cout;
using std::endl;
using std::string;
string fOutFileName("gaintest.root");
int main()
{
std::ifstream file1("data_p30.dat");
double intensity;
int i;
int j ;
double c[1000][1000];
if (file1.is_open()) {
file1.seekg(0);
while (!file1.eof()) {
file1 >> i >> j >> intensity;
c[i][j]=intensity;
cout<<c[i][j]<<'/n';
}
file1.close();
} else cout << "Error, cannot open file 1";
}
所以最終我希望能夠有一個與強度相關的2D數組。 關於我為什么失敗的任何想法? 它編譯得很好但是當它運行時,它看起來像這樣:
root [0]
*** Break *** segmentation violation
===========================================================
There was a crash.
This is the entire stack trace of all threads:
===========================================================
#0 0x0000003701098c05 in waitpid () from /lib64/libc.so.6
#1 0x000000370103c481 in do_system () from /lib64/libc.so.6
#2 0x00002b036f5ebc6a in TUnixSystem::StackTrace() ()
from /batchsoft/root/root528-x86_64-slc5-43/lib/libCore.so
#3 0x00002b036f5eb63c in TUnixSystem::DispatchSignals(ESignals) ()
from /batchsoft/root/root528-x86_64-slc5-43/lib/libCore.so
#4 <signal handler called>
#5 0x00002b0370acd515 in TRint::Run(bool) ()
from /batchsoft/root/root528-x86_64-slc5-43/lib/libRint.so
#6 0x000000000040106d in main ()
===========================================================
The lines below might hint at the cause of the crash.
If they do not help you then please submit a bug report at
http://root.cern.ch/bugs. Please post the ENTIRE stack trace
from above as an attachment in addition to anything else
that might help us fixing this issue.
===========================================================
#5 0x00002b0370acd515 in TRint::Run(bool) ()
from /batchsoft/root/root528-x86_64-slc5-43/lib/libRint.so
#6 0x000000000040106d in main ()
===========================================================
在C ++中
double c[1000, 1000];
拋棄前1000個,編譯器為以下代碼生成代碼:
double c[1000];
你寫的[1000,1000]是Pascal中的一個多維數組,但不是C ++中的數組。 在C ++中,您將使用:
double c[1000][1000];
您顯示的錯誤由ROOT生成。 由於這不是ROOT論壇,ROOT是由CERN科學家開發的c ++數據分析框架。 對於好奇,他們的網站就在這里 。 但是,您的問題與ROOT無關。
2D數組由聲明
double a[2][2];
這對你有用。
也許更安全的是使用模板類
std::vector<double> v;
對於2D應用程序,這看起來像
std::vector<std::vector<double> > v2;
這樣做的好處是可以根據需要調整其大小
v.push_back(d);
將向量的末尾添加一個元素,必要時將其拉長。 也可以使用數組語法來訪問元素
v[1]
要么
v2[1][2]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.