Reprinted] use the fstream of C ++ to read text files with structured strings and mixed numeric values

Source: Internet
Author: User

Because it is necessary to frequently access text files with mixed strings and values, it is a headache for me to effectively read such files. However, I learned the log [1] today. the solution is as follows.

The target file dat.txt is as follows:

Zzz 8 10.0 2.5 2.55

Llz 10 20.2 3.9 4.96

The read/write method is programmed as follows:

# Include <fstream>

# Include <iostream>

Using namespace STD;

Void main ()

{

Ifstream fin;

Char name [20];

Int inum;

Float fnum [3];

Fin. Open ("dat.txt"); // open the file to be read

If (Fin. Good () // you can check whether the image is successfully opened.

{

While (! Fin. EOF ())

{

Fin> name; // read the string

Fin> inum; // read integer values

For (INT I = 0; I <3; I ++)

{

Fin> fnum [I]; // read floating point cyclically

}

Cout <name <''<inum <'' <fnum [2] <Endl; // check whether the result is correct.

}

}

Else

{

Cout <"file can't open" <Endl;

}

Fin. Close (); // close the file

}

The running result is as follows:

Zzz 8 2.55

Llz 10 4.96

Press any key to continue



Reference address:Http://blog.sciencenet.cn/blog-481152-433178.html

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.