获取换行符

来源:互联网 发布:网络高清电视播放器 编辑:程序博客网 时间:2024/05/16 15:32

写了一个将一个文本的内容复制到另一个文本中的程序,发现换行符无法获取,查了一下,发现了两个解决方法

1.在换行的地方手动添加换行

2.用fget()函数

char * fgets ( char * str, int num, FILE * stream );

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or a the End-of-File is reached, whichever comes first.
A newline character makes fgets stop reading, but it is considered a valid character and therefore it is included in the string copied to str.
A null character is automatically appended in str after the characters read to signal the end of the C string.

C/C++ code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* fgets example */
#include <stdio.h>
 
int main()
{
   FILE * pFile;
   char mystring [100];
 
   pFile = fopen ("myfile.txt" "r");
   if (pFile == NULL) perror ("Error opening file");
   else {
     fgets (mystring , 100 , pFile);
     puts (mystring);
     fclose (pFile);
   }
   return 0;
}



以下是实现程序

#ifdef WIN32

#pragma warning(disable:4514 4786)
#endif//vc6.0中warning C4786:identifier was truncated to '255' characters in the debug information的解决办法


#include <iostream>
#include <string>
#include <vector>
#include <fstream>




using namespace std;
int main()


{
ifstream ifile;
ifile.open("1.txt");//读出文本文件 1.txt 中的内容,如果不是工程文件中的文本,请写清楚文件路径
fstream file("2.txt",ios_base::out);//打开文件,如果文件不存在,则创建
if(!ifile.is_open()||!file.is_open())
{
cout<<"打开文件失败"<<endl;
return 0;
}

vector<string> wl;//存放取出来的单词
string s;
string temp;
while(getline(ifile,s))//无法获取换行符,可以自己添加
{


wl.push_back(s);
cout<<s<<endl;
file<<s<<endl;//输入到文件时可以自己添加换行符
}


ifile.close();
file.close();


system("start 1.txt");
system("start 2.txt");
//用这个方法打开filename文件更简单,但是要注意filename文件不能被使用,所以使用前要file.close()文件


return 1;
}
0 0
原创粉丝点击