C + + Learning Note-c++ Read and write to TXT file

Source: Internet
Author: User

I. Input and output of the file

Header file FStream defines three types of supporting files Io:ifstream reading data from a given file, Ofstream writing data to a given file, and fstream reading to the specified data. These types are like the operations of CIN and cout, we can read and write files with the IO operator, and we can use Getline to fetch data from a ifstream.

1. Getline () function

The function prototypes for Getline are:

[CPP]View Plaincopy
    1. istream& Getline (istream& is, string& str, char delim);
    2. istream& Getline (istream&& is, string& str, char delim);
    3. istream& Getline (istream& is, string& str);
    4. istream& Getline (istream&& is, string& str);

Usually we use the Getline function to read an entire line, which takes an input stream and a string object, and the function reads the content from the given input stream until it encounters a newline character, and then deposits the read into a string object.

In addition, when the function is istream& getline (istream& is, string& str, char delim), the function encounters Delim also stops.

2. Using File Stream objects

When we want to read a file, we can define a file stream object and associate the object with the file, each of which defines a member function called open to complete a series of system-related operations.

The prototype of the Open function is:

[CPP]View Plaincopy
    1. VOID Open (const char* filename, ios_base::openmode mode = ios_base::out);
    2. VOID Open (const string& filename, Ios_base::openmode mode = ios_base::out);

There are several types of file modes (mode):

[CPP]View Plaincopy
    1. Ofstream outfile ("E:\\out.txt", Ofstream::app);

The code above opens the OUT.txt file, and if it does not exist, the system creates the TXT file and navigates to the end of the file.
Open files must be closed after use, FStream provides the member function close () to complete this operation.

Example: reading data from a hello.txt file and writing it to OUT.txt

[CPP]View Plaincopy
  1. #include "stdafx.h"
  2. #include <vector>
  3. #include <string>
  4. #include <fstream>
  5. #include <iostream>
  6. Using namespace std;
  7. int _tmain (int argc, _tchar* argv[])
  8. {
  9. Ifstream myfile ("E:\\hello.txt");
  10. Ofstream outfile ("E:\\out.txt", Ofstream::app);
  11. string temp;
  12. if (!myfile.is_open ())
  13. {
  14. cout << "File not successfully opened" << Endl;
  15. }
  16. While (Getline (myfile,temp))
  17. {
  18. outfile<<temp;
  19. }
  20. Myfile.close ();
  21. return 0;
  22. }



Two, a string stream

The string header file defines three types to support memory Io,istringstream writing data to a string, Ostringstream reading data from a string, StringStream can read data from a string or write data to a string, just as a string is an IO stream.

1, the use of Istringstream

[CPP]View Plaincopy
  1. #include "stdafx.h"
  2. #include <string>
  3. #include <sstream>//header files required for the use of Istringstream
  4. #include <iostream>
  5. Using namespace std;
  6. int _tmain (int argc, _tchar* argv[])
  7. {
  8. String str = "I am a Boy";
  9. Istringstream is (str);
  10. string S;
  11. While (is >> s)
  12. {
  13. cout << s << endl;
  14. }
  15. return 0;
  16. }

The output is:

I

Am

A

Boy

Example: Write a program that saves rows from a file in a vector<string>, and then uses Istringstream to read a data element from a vector, reading one word at a time.

[CPP]View Plaincopy
  1. #include "stdafx.h"
  2. #include <vector>
  3. #include <string>
  4. #include <fstream>
  5. #include <sstream>
  6. #include <iostream>
  7. Using namespace std;
  8. int _tmain (int argc, _tchar* argv[])
  9. {
  10. Vector<string> VEC;
  11. Ifstream myfile ("E:\\hello.txt");
  12. string temp;
  13. if (!myfile.is_open ())
  14. {
  15. cout << "File not successfully opened" << Endl;
  16. }
  17. While (Getline (myfile,temp))
  18. {
  19. Vec.push_back (temp);
  20. }
  21. For (Auto it = Vec.begin (); It! = Vec.end (); it++)
  22. {
  23. cout << *it << Endl;
  24. }
  25. cout << "-----------------use Istringstream------------------------" << Endl;
  26. For (Auto it = Vec.begin (); It! = Vec.end (); it++)
  27. {
  28. Istringstream record (*it);
  29. string S;
  30. While (record >> s)
  31. cout << s << endl;
  32. }
  33. return 0;
  34. }

Operation Result:

The following discussion is transferred from www.cndev-lab.com, program author: Guan Ning

[CPP]View Plaincopy
  1. #i nclude <iostream>
  2. #i nclude <sstream>
  3. Using namespace std;
  4. int main ()
  5. {
  6. Istringstream ISTR;
  7. Istr.str ("1 56.7",);
  8. //The above two processes can be simply written as Istringstream istr ("1 56.7");
  9. cout << istr.str () <<endl;
  10. int A;
  11. float B;
  12. istr>>a;
  13. cout<<a<<endl;
  14. istr>>b;
  15. cout<<b<<endl;
  16. System ("pause");
  17. }

In the above example, when constructing a string stream, the space becomes the internal boundary of the string parameter, and the input "assignment" operation of a A/b object in the example proves this, and the space of the string becomes the decomposition point of the integer data and the floating-point data. Using the method of demarcation we actually completed the split conversion process of string-to-integer object and floating-point object.

The use of the STR () member function allows the Istringstream object to return a string string, such as the output operation in this example (Cout<<istr.str ();).

2, the use of Ostringstream

Ostringstream is also constructed from a string object, and the Ostringstream class inserts a character into a string.
The Ostringstream constructor is as follows:

[CPP]View Plaincopy
    1. Ostringstream::ostringstream (string str);

The following discussion is transferred from www.cndev-lab.com, program author: Guan Ning

[CPP]View Plaincopy
  1. #i nclude <iostream>
  2. #i nclude <sstream>
  3. #i nclude <string>
  4. Using namespace std;
  5. int main ()
  6. {
  7. Ostringstream Ostr;
  8. //ostr.str ("abc");//If a string parameter is set at the time of construction, then the increment operation does not increase from the end, but modifies the original data, and the excess portion grows
  9. Ostr.put (' d ');
  10. Ostr.put (' e ');
  11. ostr<<"FG";
  12. String gstr = Ostr.str ();
  13. cout<<gstr;
  14. System ("pause");
  15. }

In the previous example code, we can continuously insert a single character or string into the ostr by using the put () or left-shift operator, and return the full string data after the growth through the STR () function, but it is worth noting that when the object is constructed with string data in it, Then the growth operation will not increase from the end, but modify the original data, beyond the growth of the part.

C + + Learning Note-c++ Read and write to TXT file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.