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;
}

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).

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.