Thread: fstreams

  1. #1
    UpTooLate
    Join Date
    Feb 2008
    Location
    New York
    Posts
    32

    Question fstreams

    I am trying to write a program to practice for an upcoming test that is supposed to take in these names and numbers from a file and then take the average of all the numbers of the file. I am not allowed to use getline. Our teacher hinted that you can use cin to stuff 2 things on one line like this;
    int x, y;
    cin >> x >> y;
    but I'm not sure how that works.

    The file (Sect51.dat) looks something like this:
    Will 66
    Matthew 85
    Andy 97
    Sarah 24
    Rachel 76
    Mandy 94

    This is what I have so far, but it is not working.
    Code:
    #include <fstream>
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	ifstream WOW;
    	WOW.open("Sect51.dat");
    	string x;
    	int y, aNumber;
    	int count = 0;
    	while (WOW >> aNumber)
    	{
    		cin >> x >> y;
    		count++;
    		y += y;
    		
    	}
    	cout << "The average is " << y / count << "." << endl;
    	return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So, every loop you try to read (1) aNumber, (2) x, and (3) y. But ... there's not three things on each line. So don't try to read aNumber.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Also, you're using cin, but that's for console input. Use your ifstream for file input.

    And pay attention to the values y will have as the loop progresses.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. fstreams
    By Amyaayaa in forum C++ Programming
    Replies: 9
    Last Post: 06-10-2008, 12:00 PM
  2. Overloading fstream's << and >> operators
    By VirtualAce in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2007, 03:17 AM
  3. how do I make fstream's >> work for my class?
    By MathFan in forum C++ Programming
    Replies: 3
    Last Post: 04-25-2005, 12:01 PM
  4. Problems with fstreams.
    By mosdef in forum C++ Programming
    Replies: 7
    Last Post: 06-19-2002, 03:36 PM
  5. trying to use fstreams... specifically input.seekg
    By sarahbee in forum C++ Programming
    Replies: 1
    Last Post: 01-29-2002, 01:59 AM