c++oding="utf-8" ?>
本篇文章主要讲述了用c++实现逐行读取txt文件中的字符串以及文件文本的复制,具有一定参考价值,感兴趣的朋友可以了解一下,希望对你的学习有所帮助。
逐行读取txt文件中的字符串,代码如下
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
int main()
{
ifstream in("1.txt");
string filename;
string line;
if(in) // 有该文件
{
while (getline (in, line)) // line中不包括每行的换行符
{
cout <p>文件文本的复制,将1.TXT中的内容复制到2.TXT,代码如下:</p>
<pre class="brush:css;toolbar:false">#include <fstream>
#include <string>
#include <iostream>
using namespace std;
void fileCopy(char *file1, char *file2)
{
// 最好对file1和file2进行判断
ifstream in(file1);
ofstream out(file2);
string filename;
string line;
while (getline (in, line))
{
out <p>上述程序只能针对文本文件(不仅仅是.txt),对其它类型的文件不适合。</p>
<p>本文代码都在Windows/VC++6.0下测试过, 在linux/g++下也没有问题。 </p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/gongju/2823" title="C++14"><img
src="https://img.php.cn/upload/manual/001/431/639/6ac8b33c327c4749.png" alt="C++14" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="overflowclass">C++14</a>
<p class="overflowclass">C++14 对 C++11 的修正与增强版本,适合旧系统维护和较老工具链兼容。</p>
</div>
<a rel="nofollow" href="/xiazai/gongju/2823" title="C++14" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<p>但是请一定<strong>注意</strong>linux和Windows文件格式的<strong>区别</strong>:</p>
<p> 1. 当linux上的代码读取Windows文件格式时, 读取结果的每行都会多一个\r。</p>
<p> 2. 当Windows上的代码读取linux格式文件时, 读取的结果会显示只有一行。</p>
<p>相关教程:<a href="http://www.php.cn/course/list/38.html" target="_self">C++视频教程</a></p></iostream></string></fstream>
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










