Using C++ ifstream extraction operator>> to read formatted data from a file

后端 未结 4 1515
栀梦
栀梦 2020-12-30 06:46

As my learning, I am trying to use c++ ifstream and its operator>> to read data from a text file using code below. The text file outdummy.txt has following contents:

4条回答
  •  醉酒成梦
    2020-12-30 07:36

    Since you have elected to use C-strings, you can use the getline method of your ifstream object (not std::getline() which works with std::strings), which will allow you to specify the C-string and a maximum size for the buffer.

    Based on what you had, and adding an additional buffer for the second line:

    char buf[100];
    char buf2[100];
    
    in.getline(buf,sizeof(buf));
    in.getline(buf2,sizeof(buf2));
    in >> a;
    

    However, as the other poster has proposed, try using the std::string and its methods, it will make your life easier.

提交回复
热议问题