As you see i'm a newbie who studies on GEANT4 simulation program. I need an array which has numbers on it for example my_array[120][1]. The question is, i exported this numbers from some licensed program as a text file to use in my simulation. This text file has unique format, you can see it by clicking the link.
I want to separate lines which are named as "Leaf" and store just their numerical values into an array. How can i do that? I wrote some codes in order to writing "Leaf" lines into a file. It worked but i couldn't write them into an array as just numbers.. When i tried it didnt work cause the lines are all in string format. And i couldn't separate the lines as strings and integers in order to store into an array.
#include <iostream>
#include <fstream>
#include <sstream>
usingnamespace std;
int main()
{
// Defining constants and Variables
string Line_1;
string Line_2;
int Row, Col;
char MLC_Array[150][150];
ifstream My_MLC ("MLC_File.mlc");
ofstream myMLC_File ("MLC_Son.txt");
if (My_MLC.is_open())
{
Row=0;
while (!My_MLC.eof())
{
getline(My_MLC, Line_1);
string stringvalue = "Leaf";
if (Line_1[0] == stringvalue[0]){
if (Line_1[1] == stringvalue[1]){
if (Line_1[2] == stringvalue[2]){
myMLC_File << Line_1 << '\n';
}
}
}
}
My_MLC.close();
}
else cout << "File can not open, be sure that the file is on their direction or not.";
myMLC_File.close();
Somehow your approach look far too complicated. I would rather do it like this.
1 2 3 4 5 6 7 8 9 10 11
ifstream My_MLC ("MLC_File.mlc");
// TODO check for error
strong line;
while(getline(My_MLC, line))
{
if (line.find("Leaf") != string::npos)
{
// now you need to find the '=' and copy everything after into a tmp string
// and convert this tmp string into a double
}
}
BTW It's better to use a vector instead an array - unless you really really have to use an array.
if (My_MLC_2.is_open())
{
string Line_2;
string TMP;
while (!My_MLC.eof())
{
while(getline(My_MLC_2, Line_2))
{
if (Line_2.find("Leaf") != string::npos)
{
if (Line_2.find("=") != string::npos)
{
TMP << Line_2;
cout << TMP << '\n';
}
}
}
}
}
Try to see what comes as output but couldn't do it.. And also how to define values as a Vector? I am actually a Matlab user and things get really complicated to me in C++.
if (Line_2.find("=") != string::npos)
You need to store the value of find and then use substr to copy the rest of the string into TMP and convert into double. It would be good if you can post the file in text so someone can copy it and run the code.