Hello, I'm new to c++ and i'm making program to read from numbers from file and calculate average.
The numbers in file is like this

10; 15; 200

and my source so far

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("numbers.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 


  system("PAUSE");
  return 0;
}

So, can anyone explain me, how convert that string to few ints in order to calculate average?
Thanks in advance

Recommended Answers

All 4 Replies

[edited]

Hello markee,
ASCII value of character 0 is 48 and '1' is 49. When you subtract these ASCII values you will get the required value 1.
For example,

char a;
int b;
b=int(a)-'0';

A few options.

  1. Read a line at a time from the file as a string. Parse the string. Extract the numbers. Convert as needed.
  2. Read individual numbers in one at a time as a string, using ';' and '\n' as delimiters. Convert strings to integers using atoi, strtol, or similar.
  3. Assuming there are always exactly 3 numbers on a line, each separated by a semicolon, read from the file directly into integer variables, then read in a char at a time, till you get to the semicolon, throw it away, read in another number, get the semicolon, throw it away, read the last number.

My personal preference is #1. Read the whole line in as a string. Replace all semicolons in that string with spaces. Create a stringstream from the new string. Read from the stringstream directly into the integer variables.

For a newbie who isn't familiar with stringstreams or string parsing, either learn them or go with #3.

VernonDozier, thank you, i'll use your way #1.
Thank you very much :)

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.