I am writing a program that will do some math on some data I have in a file. The problem is that there is different types of data in the file. The data looks like this:
How would I do that? If a string can hold all of this, how do I do it? Do I create an array of strings? I am sorry, I am very new to C++, and have a little bit more experience with Java, but not familar with the weird string objects of the C language.
Do you know of any place where I can get some more detailed examples of how to use that? I read the page, but am still quite confused. I have googled this problem many times, and am still at a loss. I don't have a lot of knowledge with these class based languages.
Alright, I've been trying to use getline to get a the columns into an array, i went ahead and separated the data into 3 files so it would be easier (i am newbie).
The code I was using made an array of strings, however I need to do mathematical functions on it.
How do I change it from an array of strings to a float so that I can perform operations on it? Or, how do i modify my code so that it will be an array of floats from the very beginning? It seems that getline only works for strings...
int main()
{
string dmArray[123];
string NAMEArray[123];
string LONGAArray[123];
string LATAArray[123];
double DMArray[123];
ifstream dmfile ("DM.txt");
ifstream namefile ("names.txt");
ifstream longafile ("longa.txt");
ifstream latafile ("lata.txt");
ofstream mofile ("dmodel.txt");
if (dmfile.is_open())
{
for (int i = 0; i < 123; i++)
{
getline (dmfile,dmArray[i]);
}
dmfile.close();
DMArray[123] = atof(dmArray[123].c_str());
cout << DMArray[123] << endl;
}
else cout << "unable to open DM file";
system("PAUSE");
return 0;
}
The problem here is a few. When I try to cout the DMArray[123] which should be in double format, it only returns "0".
However, when I try to cout dmArray[123] which is an array of strings, that should've been transformed by the point I try to cout it, it puts lots of weird symbols on the screen and my speakers start beeping frantically until windows shuts down.
How do I properly convert this array of strings to a double array so that I can perform mathematical operations on it?
As far as I know you would have two options, but I'm sure some of the experts around here could tell you the best solution.
- You could use stringstreams and output the data into floats from there (just have a look at this site's tutorial pages where it has some examples).
- You could use the function sscanf() on your string, which is not true c++, but a C function, but should work nonetheless. More on that here: http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/