I joined this forum today and for past 10 days or so am using the valuable information related to c++ from the tutorials(I started learning the language few days ago). I would appreciate if you can take a look at this code and point me in right direction.
Background:
> This code asks user to input a text file.
> It reads the data line by line
> I then save the array in csv format (, separated) and also print it out in console
> It starts matlab engine and using the API does some calculations/plots and then closes the engine. This works as well. (am using VS-2008 and pointing to the include and lib folders for matlab there). But this info is not really important for issue at hand.
Problem: Here is the sample txt that I read:
1 2.718281828
2 7.389056099
3 20.08553692
4 54.59815003
5 148.4131591
6 403.4287935
7 1096.633158
8 2980.957987
9 8103.083928
10 22026.46579
Here is how the text appears in the console and in csv.
1 2.71828
2 7.38906
3 20.0855
4 54.5982
5 148.413
6 403.429
7 1096.63
8 2980.96
9 8103.08
10 22026.5
Comment: It seems that the decimals get truncated to accomodate the total number
of digits or characters. This is not what anyone would want. It seems that the piece of code that is reading the data itself is doing something wrong.
I hope as a first timer I explained the scenario in the best possible way. If you feel the information is not adequate then please let me know. I would appreciate a oneliner, pointing me to right direction.
Thanks
and apologies if this is a stupid question.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip> //in case setting width. use later on
#include <windows.h>
#include <cstdlib>
#include <engine.h> // matlab engine
You just need to specify the required number of significant digits.
either this style:
cout << setprecision(10);
or like this:
fout.precision(10);
Do that just once before beginning the output to console or file.
An unrelated issue, this loop structure is redundant,
1 2
while(filename.good())
{
At most, you might want an if statement there. But the previous section of the code has already checked the file was opened (and ended the program if there was an error), so even an if statement is not needed.