//final.cpp
//Creates an array with 2 players' batting avg
//Read in hits and atbats for each player
//1)	one player get data in main           
//2)	other get data in battingavg function
//battingavg function figures out battingavg for both players
// and puts them in array (not hits & abats), print out array in function
#include <iostream>           //  Rose 309 611           Jack 250 689

//COMPILE ERROR???? G:\C++\HW\final.cpp In function `int main()': 

#include <fstream.h>
#include <stdlib.h>
using namespace std;

void BattingAverage(int hits, int atbats, int count);     //&????
float batavg[2];
int hits, atbats, count;
char name;

int main() 
{
   ifstream inbat;
   ofstream outbat;

   inbat.open("inbat.txt");
   outbat.open("outbat.txt");

   if ( inbat.fail() )
   {
      cout<<"Output file doesn't exist!";
   }
   for ( int count=0; count<2; count++ )
   {
      inbat.getline(name,5);        //ERROR: 35 G:\C++\HW\final.cpp invalid conversion from `char' to `char*' 
      //32 G:\C++\HW\final.cpp   initializing argument 1 of
      // `std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::getline(_CharT*, std::streamsize) [with _CharT = char, _Traits = std::char_traits<char>]' 
      inbat>>hits>>atbats;

      BattingAverage(hits, atbats, count); //calling function to do calc	

   }                   
   system("PAUSE");
   inbat.close();
   return 0;
}
void BattingAverage(int hits, int atbats, int count) 
{
   batavg[count] = (float)hits/(float)atbats;      

   cout<<name<<"'s batting average is:"<<batavg[count]<<endl;      //ios
}

<< moderator edit: added [code][/code] tags and fixed indentation >>


Thank you so much for your help

Dani AI

Generated

Short diagnosis and the root causes. The original compile error came from declaring name as a single char; changing to a tiny fixed-size char array fixes compilation but can silently truncate names. The reason the second name (and subsequent averages) looked wrong is that the program mixes formatted input (operator>>) with unformatted input (getline). After operator>> reads the integers it leaves the newline in the stream, so the next getline immediately returns an empty string. caught the single-char problem and was pointing toward the leftover-newline behavior.

Two safe approaches (pick one depending on your input file layout).

If each record is a single line like "Rose 309 611", read the whole line and parse it with an istringstream:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>

std::ifstream in("inbat.txt");
std::string line;
while (std::getline(in, line)) {
    std::istringstream iss(line);
    std::string name;
    int hits, atbats;
    if (!(iss >> name >> hits >> atbats)) continue; // malformed line
    float avg = static_cast<float>(hits) / atbats;
    std::cout << name << "'s batting average is: " << avg << '\n';
}

If the file uses two lines per player (name on its own line, numbers on the next), keep using getline for the name but consume the leftover newline after reading the ints:

#include <fstream>
#include <iostream>
#include <limits>
#include <string>

std::ifstream in("inbat.txt");
std::string name;
while (std::getline(in, name)) {
    if (name.empty()) continue;
    int hits, atbats;
    if (!(in >> hits >> atbats)) break;
    in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // drop newline so next getline works
    float avg = static_cast<float>(hits) / atbats;
    std::cout << name << "'s batting average is: " << avg << '\n';
}

Small best-practice notes: prefer std::string over fixed char buffers; avoid globals and shadowed variables (pass the name into your BattingAverage function or return results); always check atbats != 0 before dividing; use modern headers (<fstream>, <string>, etc.) and avoid system("PAUSE"). These changes will stop the truncation/empty-name symptoms that reported and make the averages correct and stable.

Recommended Answers

All 8 Replies

Are you only using a single letter for the name of the player?

If not, then you should change

char name;
to
char name;


(where size is the number of letters required to store the name + 1 for the null terminator)

>char name;
Good suggestion, bad code. You seem to be mixing and matching features of C++ and Java to create something completely incorrect for both. Try this instead:

char name[size];

Where size is a suitably defined constant value, in this case 5.

You're right - I should stick to doing one language well instead of doing more than one language not so well...

Still doesn't work -thanks for help. By changing to char name[5] - Not reading in 2nd name and not doing calculation correctly for either. Thanks again

*sigh* If I had a nickel for every time someone left a newline in the stream with cin>> or scanf, I would be rich by now.

Sorry Narue but as I'm sure you can tell, I am a beginner and have no idea what you are saying. Can you tell me in very basic C++ words. Thanks, Kittie

>Can you tell me in very basic C++ words.
Enter get stuck in cin, break rest of program.

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.