【问题标题】:Using int alongside string and getline without errors将 int 与 string 和 getline 一起使用而不会出错
【发布时间】:2020-01-14 15:24:05
【问题描述】:

我正在创建一个程序,它从文件中读取作者、标题和卷数并打印出标签,

(例如。 亚当斯 完整的世界史 第 1 卷,共 10 卷

亚当斯 完整的世界史 第 2 卷,共 10 卷等)

为了使其正确读取而不是无限循环,我必须将所有变量更改为字符串。但是,为了将来参考卷号,我需要它是 int 以便我可以比较数量。 我对使用 do-while 循环改进代码的想法进行了注释,以说明为什么我希望 vnum 具有 int 值。

#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{

        ifstream fin;
        string author;
        string title;
        string vnum;
        int counter=1;

   fin.open("publish.txt", ios::in);


   while (!fin.eof())
   {
       getline(fin, author);
       getline(fin, title);
       getline(fin, vnum);

       //do
       //{
           cout << author << endl;
           cout << title << endl;
           cout << "Volume " << counter << " of " << vnum << endl;
           cout << endl;
           //counter++;
       //} while(counter < vnum);

   }
   fin.close();
   return 0;

}

我正在读取的文件:

亚当斯

完整的世界历史

10

塞缪尔

我的犯罪生涯

2

鲍姆

巫师故事

6

【问题讨论】:

标签: c++ file while-loop do-while getline


【解决方案1】:

首先,避免使用

while (!fin.eof())

请参阅Why is “while ( !feof (file) )” always wrong? 以了解它会导致的问题。

来到你的任务,我建议:

  1. 创建一个struct 来保存数据。
  2. 添加一个函数以从std::istream 中读取struct 的所有成员。
  3. 添加一个函数,将struct的所有成员写入std::ostream
  4. 简化main 以使用上述内容。

这是我的建议:

struct Book
{
   std::string author;
   std::string title;
   int volume;
};

std::istream& operator>>(std::istream& in, Book& book);
std::ostream& operator<<(std::ostream& out, Book const& book);

这将有助于将main 简化为:

int main()
{
   ifstream fin;
   Book book;

   // Not sure why you would need this anymore.
   int counter=1;

   fin.open("publish.txt", ios::in);

   while  ( fin >> book )
   {
      cout << book;
      ++counter;
   }

   return 0;
}

读写Book的函数可以是:

std::istream& operator>>(std::istream& in, Book& book)
{
   // Read the author
   getline(in, book.author);

   // Read the title
   getline(in. book.title);

   // Read the volume
   in >> book.volume;

   // Ignore rest of the line.
   in.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

   return in;
}

std::ostream& operator<<(std::ostream& out, Book const& book)
{
   out << book.author << std::endl;
   out << book.title << std::endl;
   out << book.volume << std::endl;

   return out;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2015-04-27
    • 1970-01-01
    • 2012-08-21
    • 2021-04-06
    • 2013-01-24
    • 2020-10-21
    相关资源
    最近更新 更多