C++从txt文本中输入和读取字符串

  文件的关联

   文件操作首先需要包含头文件 fstream

            fstream头文件中定义用于输入的ifstream类和用于输出的ofstream类。

   可以通过使用这两个类来声明对象:

                 ifstream in_file;

                 ofstream out_file;

   将我们声明的对象与文件关联起来:

                 out_file.open(“name.txt”);

                 in_file.open(“name.txt”);

          Ps:打开的文件最后一定要关闭。例如:out_file.close();


下面的例子包含了向文件输入字符串和从文件读取字符串:

#include 
#include 
#include 
using namespace std;
main()
{
    char filename[20];           //定义文件名字符数组
    ofstream out_file;

    cout << "Enter file name: "; //输入文件名
    cin >>filename;
    out_file.open(filename);     //使ouffile关联文件
    cout << "Please enter string(q to quit): "<

运行结果:

C++从txt文本中输入和读取字符串_第1张图片
从 apple 一直到 orange 都是输入的字符串 并在输入完成后 按 q 并回车就会退出输入,然后打印出我们输入的字符串。

在上例中使用 getline(in_file,item); 从文件中读取字符串存入item 中。


这一次只从文件中读取:

#include 
#include 
#include 
using namespace std;

main()
{
    char filename[20];      
    cout << "Enter file name: ";    
    cin >>filename;            //输入文件名

    ifstream in_file;

    in_file.open(filename); //关联文件

   string item; getline(in_file,item,';'); //从文件中获取以'\n'为结尾的字符串 
    while(in_file) 
   { 
        cout <

运行结果:

C++从txt文本中输入和读取字符串_第2张图片

   在本例中可以看到getline(in_file,item)中加入了’;’ 意思是; 号为字符串读取的结尾点

   如果不设置结尾点则像第一个程序一样则会默认为以 \n 字符为结尾点

   通过运行可以看到每次读取时遇到 ; 则停止读取

   可能有人会疑惑在 strawberry mango 之间并没有号,那为什么也会换行输出,

   而不是像pineapple peach一样连在一起输出呢?

   因为当设置了停止符号 ; 号后'\n' 将不会起作用且会被当作字符存入字符串中。在输出字符串的时候起作用。


你可能感兴趣的:(C++)