We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you two Citrix podcasts. Learn about 2020 trends and get answers to your biggest Citrix questions!Listen Now

x

Reading numbers and characters from a file

emmagaya
emmagaya asked
on
Medium Priority
251 Views
Last Modified: 2012-05-06
I have a program that contains female and male student examination
results. The letter code f is used for female students and m for male students. Every file
entry consists of a letter code followed by an examination result. Each line has one entry. The number of entries
in the file is unknown. Write a program that computes and outputs the average examination result for both male
and female students. Prompt the user for the name of the file that contains the examination results that have to
be processed.
Example:
m 25
f 100
f 14
m 32


I have written the program structure as below. I need help in reading and manipulating the text from the file - i.e. in reading the marks line by line and computing them.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
 
int main()
{
    string line;
    ifstream mymarks ("marks.txt");
 
    if (mymarks.is_open())
    {
      while (getline (mymarks,line))
      {
       for (int i=0; i < line.length(); i++)
        {
       
            cout << line << endl;
       
        }
      }
      mymarks.close();
    }
    else cout << "Unable to open file";
     
      return 0;
}

Open in new window

Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2009

Commented:
Up till the while loop with getline, your code is ok.

Just the while loop body needs a bit more work.

What you need to do now, is extract the 'f' or 'm' character from the beginning (the first character of the line string). And after that, extract the integer value from the line.
atoi could help for this :

        http://www.cplusplus.com/reference/clibrary/cstdlib/atoi.html

or alternatively, you could make use of a stringstream.

Once you have the gender, and the integer value, you can update the statistics data.
>>>> or alternatively, you could make use of a stringstream.

feed an istringstream with the input line and try to read from that stream like

 istringstream iss(line);  // feeds the iss with line
 if (iss >> gender >> age)
 {
       // coming here all is ok
 }
 else
 {
       // either gender or age was bad
  }

The istringstream needs <sstream> to include.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
CERTIFIED EXPERT
Top Expert 2009

Commented:
emmagaya,

When accepting an answer, it's important to choose those post(s) that answered the question (note that you can choose more than one post from more than one expert).

It is also important to choose an appropriate grade, which reflects the usefulness of the answer. If the question was fuly answered, then an A grade is appropriate. If something was missing, it's generally advised to continue working with the experts, and allow them to earn an A grade.

Author

Commented:
The answer by itsmeandnobodyelse: gave me ideas but it did not fully help me solve the problem which I had. But thanks for the advice infinity08
CERTIFIED EXPERT
Top Expert 2009

Commented:
You can still choose to continue this question. If you have further doubts/questions about this, we'll be glad to answer them.

Since it apparently did not fully help you solve the problem, there's no reason to close the question. After all, we're here to help you :)

Author

Commented:
Ok, thanks for that. I have tried using streams but did not manage getting the program to read the characters differently - the character first and then the number and then manipulate this data.

Thats were my main challange is.
CERTIFIED EXPERT
Top Expert 2009

Commented:
Can you show the code you tried ?
Putting your code and mine together you should have somewaht like
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using namespace std;
 
 
int main()
{
    string line;
    ifstream mymarks ("marks.txt");
 
    if (mymarks.is_open())
    {
      while (getline (mymarks,line))
      {
       for (int i=0; i < line.length(); i++)
        {
       
            cout << line << endl;
            istringstream iss(line);  // feeds the iss with line
            int points = 0;
            char gender = ' ';
            if (iss >> gender >> points)
            {
              // coming here all is ok with reading
              if (gender != 'm' && 'gender != 'f') continue;
              // now you could store both in an array you defined outside
              //   arrMarks.push_back(pair<char, int>(gender, points));
              // or maybe you want to build the counts and sums like
              // if (gender == 'm') { count_m++; total_m += points; }
              // if (gender == 'f') { count_f++; total_f += points; }
            }
            else
            {
               // either gender or points was bad
               // ignore it
               continue;
            }
 
       
        }
      }
      mymarks.close();
    }
    else cout << "Unable to open file";
     
      return 0;
}

Open in new window

As it was an assignment I didn't give full code but only a strong hint.

If that was selected as an solution, a B grade was quite appropriate cause you would need some own efforts to solve the problem.

But if the question wasn't solved you shouldn't accept but ask more questions. Then, of course, if you finally got a full solution, an A grade was appropriate.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.