且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从文件或cin和cout读取和写入

更新时间:2023-12-02 23:23:34


  • 检查是否已成功打开文件。

  • 检查您读取的 istream 没有 failbit 设置之后,您已从中读取了该信息。由于 istream 在布尔上下文中会检查 badbit failbit 并且 std :: getline 返回与您提供的相同的 istream ,替换您的 while( cin.good())其中:

    • Check that opening the files was done successfully.
    • Check that the istream you read from doesn't have the failbit set after you've read from it. Since an istream in a boolean context checks badbit and failbit and that std::getline returns the same istream you gave it, replace your while (cin.good()) with:
      while(getline(cin, current_line)) {
          // ... only entered if badbit and failbit are false ...
      }
      



    • 也就是说,通常***创建一个单独的函数来读写通用的 istream / ostream s。这样,您就不必弄混 cin cout rdbuf / code>。

      That said, it's usually better to create a separate function for reading/writing to generic istream/ostreams. This way you don't have to mess with the rdbufs of cin and cout.

    #include <fstream>
    #include <iostream>
    #include <string>
    
    #include "Gcalc.h"
    
    void do_stuff(std::istream& is, std::ostream& os) {
        Gcalc gcalc;
        std::string current_line;
    
        while(getline(is, current_line)) {
            try {
                gcalc.implementCommand(os, current_line);
            } catch(Quit_Program& error) {
                break;
            } catch(const std::bad_alloc& error) {
                std::cerr << "Error: fatal error - " << error.what() << std::endl;
                break;
            } catch(Exception& error) {
                std::cout << error.what() << std::endl;
                // or, if you really want it:
                // os << error.what() << std::endl;
            }
        }
    }
    
    int main(int argc, char* argv[]) {
        if(argc == 1) {
            do_stuff(std::cin, std::cout);
        } else if(argc == 3) {
            std::ifstream input(argv[1]);
            std::ofstream output(argv[2]);
            if(input && output) do_stuff(input, output);
        }
    }
    

    如果要在程序运行时向用户提示交互模式下,您可以添加一个打印提示的函数,然后调用 std :: getline 。您可以在 while 循环内合并它,但是看起来很乱,所以我建议这样:

    If you want to give the user a prompt when the program is running in interactive mode, you could add a function that prints the prompt and then calls std::getline. You can combine this inside the while loop, but it looks messy, so I would suggest something like this:

    std::istream& prompt(std::istream& is, std::string& line) {
        if(&is == &std::cin) std::cout << "Gcalc> ";
        return std::getline(is, line);
    }
    
    // ...
    
        while(prompt(is, current_line)) {
            // ...
        }