Reputation: 1997
i have a problem with reading from a file, and converting content to double. I have read the solutions from stackoverflow but nothing works.
i have this input file:
1291.23
291.493
558.089
309.266
513.656
491.44
429.234
851.345
589.192
535.873
802.469
713.604
1002.42
997.973
513.656
313.709
407.018
624.738
460.337
526.986
473.667
1202.36
and the program:
#include <math.h>
#include <string>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <sstream>
using namespace std;
void main() {
char* filename = "mr1.txt";
ifstream fin;
fin.open(filename);
float d;// = 0.0;
int v = 0;
while (v < 21){
fin>>d;
if(v >= 2 || v < 15){
cout<<d<<endl;
}
v++;
}
}
the output is: 1291 for 12 times
How can i convert from these file to double without problem? Thanks!
Upvotes: 0
Views: 2962
Reputation: 1527
James Kanze has the best advice thus far as far as how to iterate through the file. But i'm pretty sure it should be:
std::cout << d << std::endl;
Otherwise you'll be printing out line numbers.
Also, I'd like to point out you have a lot of unnecessary includes. Not that it matters, but all you really need at this point is iostream and fstream. Everything else is excess.
One last thing. If you need the input to be doubles, why are you putting them into a float variable?
Upvotes: 1
Reputation: 5334
Upvotes: 1
Reputation: 490148
As a quick sanity check, try just copying the entire file to standard output, something like this:
#include <iostream>
#include <iterator>
#include <algorithm>
int main() {
std::ifstream in("mr1.txt");
std::copy(std::istream_iterator<double>(in),
std::istream_iterator<double>(),
std::ostream_iterator<double>(std::cout, "\n"));
return 0;
}
Upvotes: 1
Reputation: 153919
There are several things wrong with your code, but none which would explain the symptom you describe (which is impossible with the code you've posted: you loop 40 times, and output every time in the loop). Anyway:
What your loop probably should look like is:
while ( fin >> d ) {
if ( v >= 2 && v < 15 ) {
std::cout << v << std::endl;
}
++ v;
}
This will cause the elements [2, 15) to be displayed, provided they're present.
If you're always displaying the same value, it's probably that the input after that value failed, given that you don't test whether your input succeeded or not. One possible explination is the one moala mentionned in a note: when you open a file, it is imbued with the current global locale. Try:
fin.imbue(std::locale("C"));
immediately after opening the file; in most locales, the decimal separator is a comma, not a point. (Also: check that the open succeeded.)
Upvotes: 2
Reputation: 12651
You see the last 15 lines of the output of your program, because the v
variable continues growing over the number of lines in the data file.
Change while (v < 40)
to while(v < 21)
and you will see what you expect to see.
Upvotes: 1