[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Reading numbers and characters from a file

Posted on 2009-02-18
9
Medium Priority
?
241 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

0
Comment
Question by:emmagaya
  • 4
  • 3
  • 2
9 Comments
 
LVL 53

Expert Comment

by:Infinity08
ID: 23670593
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.
0
 
LVL 39

Accepted Solution

by:
itsmeandnobodyelse earned 375 total points
ID: 23670686
>>>> 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.

0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23803400
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.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:emmagaya
ID: 23803465
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
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23803503
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 :)
0
 

Author Comment

by:emmagaya
ID: 23803537
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.
0
 
LVL 53

Expert Comment

by:Infinity08
ID: 23803657
Can you show the code you tried ?
0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 23804429
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

0
 
LVL 39

Expert Comment

by:itsmeandnobodyelse
ID: 23804489
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.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.
The viewer will learn additional member functions of the vector class. Specifically, the capacity and swap member functions will be introduced.

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question