Pregunta

I need to use the function getline to be able to read in the spaces within a string. Currently, I'm reading word by word and any space will input the next word into a different variable. A small extract of the code is as below.

istream & operator >>( istream & input, Unit & C )
{
    input >> C.unID >> C.unName >> C.credits >> C.Result >> C.mDay >> C.mMonth >> C.mYear; 
    return input;
}


ostream & operator <<( ostream & os, const Unit & C )
{
    os << "  Unit ID:  " << C.unID << '\n';

    os << "  Unit Name: " << C.unName << '\n'
      << "  Credits: " << C.credits << '\n'
      << "  Result: " << C.Result << " marks" << '\n'
      << "  Date: " << C.mDay << " " << C.mMonth << " " << C.mYear << '\n';
    return os;
}

Note that I only need getline for unName.

As for the infile, it's in my main.cpp. Code are as below.

ifstream infile( "rinput.txt" );
  if( !infile ) return -1;

  Student R;
  infile >> R;


  ofstream ofile( "routput.txt" );

  ofile << R
    << "Number of units = " << R.GetCount() << '\n'
    << "Total credits     = " << R.GetCredits() << '\n';

The code works fine and all.

¿Fue útil?

Solución

If I understand what you are trying to do, the issue is not with your code but with how you organize your input. In your code, if you have Unit::unName contain spaces while all other fields of Unit do not contain spaces, you need to parse your line yourself. The input has to be formatted properly. For example, if you use a delimiter such as ',' in your input file/stdin that does not appear in any valid unName or unId etc., you can use

istream & operator >>( istream & input, Unit & C ) {
    input >> C.unID; getline(input,C.unName,','); input >> C.credits; ...
}

instead of,

istream & operator >>( istream & input, Unit & C )
{
   input >> C.unID >> C.unName >> C.credits >> C.Result >> C.mDay >> C.mMonth >> C.mYear; 

   return input;
}

In above, the overloaded form istream& getline (istream& is, string& str, char delim); uses a delimiter such as ',' or '\t' to replace the default \n. You need to use format your input lines with delimiters because otherwise program will not be able to tell if 200 in

1 John Smith 200

should be part of the unName field or the credits field.

So, you can change this to

1, John Smith, 200, ...

and use ',' as the delimiter or change input to

1 John Smith 200 ...

and use the default '\n' as the delimiter.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top