TransWikia.com

Как решать проблему со вводами строк? C++

Stack Overflow на русском Asked by Const_Int on December 14, 2021

Почему не вводятся длинние имена книг со пробелами? в чем проблема? помогите решить проблему

Примеры

Входные данные

2

Mother

5000 4800

Oblomov

10000 8600

4

Cosmos

4000 1000 100

Sapiens: A Brief History of Humankind

10000 380 50

A Brief History of Time

7500 460 200

The Origin of Species

4000 400 500

#include <iostream>
#include <string>
using namespace std;
 
class Book {
  public:
  string mbookName;
  
  public:
  Book() = default;
 
  Book(string& bookName) :
   mbookName(bookName)
   {
 
   }
};
 
class FictionBook : public Book {
  public:
  int mbookSoldCount;
  int mbookPrintCount;
 
  public:
  FictionBook() = default;
 
  FictionBook(string& bookName, int soldCount, int printCount) :
  Book(bookName), mbookSoldCount(soldCount), mbookPrintCount(printCount) 
            {
 
            }
 
friend std::istream& operator>>(std::istream& is, FictionBook& ficB);          
};
std::istream& operator>>(std::istream& is, FictionBook& ficB)
{
  is >> ficB.mbookName >> ficB.mbookSoldCount >>ficB.mbookPrintCount;
    return is;
}
 
class ScientificBook : public Book {
  public:
  int mbookPrice;
  int mbookPagesCount;
  int mbookCopiesCount;
 
  public:
  ScientificBook() = default;
 
  ScientificBook(string& bookName, int bookPrice, int pagesCount, int copiesCount) : Book(bookName), mbookPrice(bookPrice), mbookPagesCount(pagesCount), mbookCopiesCount(copiesCount)
  {
 
  }
  friend std::istream& operator>>(std::istream& is, ScientificBook& sciB);
};
std::istream& operator>>(std::istream& is, ScientificBook& sciB)
{
  is >> sciB.mbookName >> sciB.mbookPrice >> sciB.mbookPagesCount >> sciB.mbookCopiesCount;
  return is;
}
 
int main() {
  unsigned int n;
  cin >> n;
  FictionBook* fictBook = new FictionBook[n];
  for (int i = 0; i < n; ++i)
  {
       std::cin >> fictBook[i];
  }
  unsigned int m;
  cin >> m;
  ScientificBook* scientBook = new ScientificBook[m];
 for (int j = 0; j < m; ++j)
  {
      std::cin >> scientBook[j];
  }
 
delete [] scientBook;
delete [] fictBook;
 
return 0;
}

One Answer

Ну, примерно так (не компилировал, но вроде не опечатался...)

istream& operator>>(istream& is, FictionBook& ficB)
{
    getline(is,ficB.mbookName);
    is >> ficB.mbookSoldCount >>ficB.mbookPrintCount;
    is.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    return is;
}
std::istream& operator>>(std::istream& is, ScientificBook& sciB)
{
    getline(is,sciB.mbookName);
    is >> sciB.mbookPrice >> sciB.mbookPagesCount >> sciB.mbookCopiesCount;
    is.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    return is;
}

Answered by Harry on December 14, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP