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

来源:互联网 发布:武汉干部网络培训学院 编辑:程序博客网 时间:2024/05/18 01:17

  文件的关联

   文件操作首先需要包含头文件 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 <iostream>#include <fstream>#include <cstring>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): "<<endl;    char str[100];    cin.getline(str,100).get();  //输入文件名 并吸收最后的回车符    while(strcmp(str,"q")!=0)    //输入想要输进文件中的字符串 单独输入 q 退出输入。    {        out_file << str << endl; // 像使用cout 一样输入到文件中        cin.getline(str,100);    }    out_file.close();            // 输入完毕 关闭文件    ifstream in_file;    in_file.open(filename);    string item;    getline(in_file,item);       //从文件中获取以'\n'为结尾的字符串    while(in_file)    {        cout <<item <<endl;      //输出获取的字符串        getline(in_file,item);    }    in_file.close();             //输出完毕 关闭文件}

运行结果:


从 apple 一直到 orange 都是输入的字符串 并在输入完成后 按 q 并回车就会退出输入,然后打印出我们输入的字符串。

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


这一次只从文件中读取:

#include <iostream>#include <fstream>#include <cstring>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 <<item <<endl; //输出获取的字符串         getline(in_file,item,';');    }     in_file.close(); //输出完毕 关闭文件}

运行结果:


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

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

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

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

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

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


0 1
原创粉丝点击