954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

please help on IO and "atof"

hi all,
I am trying to figure out how to read from a file, ifstream reader reading string next.... if next is a digit then add it to total... and cout total.. please indicate what went wrong. thank you.

# include <iostream>
# include <fstream>
# include <cstring>
# include <string>
# include <cctype>


using namespace std;


int main()
{
	ifstream reader; 
	reader.open("num.txt");

	string next; 
	double total=0;
	bool digit =true; 
	
	while(reader>>next)
	{
		if(!isdigit(next))
		{
			double x= atof(next);
			total+=x;
		}

		
	}
	reader.close();
	cout<<total;


	return 0;
}
k2k
Posting Whiz
352 posts since Nov 2007
Reputation Points: 15
Solved Threads: 1
 

Your code shouldn't even compile.

>if(!isdigit(next))
next is a string, but isdigit expects an integer.

>double x= atof(next);
next is a string, but atof expects a pointer to const char.

How about something more like this:

#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <cctype>
#include <sstream>

using namespace std;

bool parse_double ( const string& s, double& value )
{
  return stringstream ( s ) >> value;
}

int main()
{
  /*ifstream reader; 
  reader.open("num.txt");*/
  istream& reader = cin;

  string next; 
  double total=0;

  while(reader>>next)
  {
    double x;
    
    if ( parse_double ( next, x ) )
      total += x;
  }

  cout<<total;

  return 0;
}

You should avoid things like atof in favor of less hairy solutions (like stringstream).

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

thx for the reply... but how this program is supposed to work? what should i input to get my text document?

istream& reader = cin; what does this line do? please provide a bit common on the codes if possible.. thank you

k2k
Posting Whiz
352 posts since Nov 2007
Reputation Points: 15
Solved Threads: 1
 

The code as written accepts keyboard input. If lines 17 and 18 are uncommented and line 19 commented out then you can use the same code to obtain input by reading from files that you used with keyboard input.

Otherwise, it's a loop that obtains input and passes that and a numerical variable to a function by reference so any changes to the variables in the called function are available in the calling function. The function converts the input string into a numerical value. The numerical value is then added to an accumulator. Once the loop is done the accumulated value is printed to the screen.

Lerner
Nearly a Posting Maven
2,382 posts since Jul 2005
Reputation Points: 739
Solved Threads: 396
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You