文件操作中使用getline函数的问题

windyxyf 2007-12-19 02:45:48
对ASCII文件操作时,我们经常用到get和put函数,那么,对于getline函数应该如何使用呢?
1.使用get和put函数时,文件指针会逐个向后移,getline函数会吗?
2.line的概念是什么,好像仍然要自己给出长度啊,如getline(ch,20)
3.例:编程序CompFile,首先让用户输入两个文件名及其路径(二文件均为text文件),而后通过使用类成员函数getline逐行读入这两个指定文件的内容并进行比较。若发现有不同,则在屏幕上显示出相异二行的行号及其内容,并暂停下来询问用户是否需要继续比较后继行,直到用户回答不需要继续进行比较,或者已经比到了二文件的结束时停止处理。

这里涉及到'行号',我不知道一行到底有多少个字节啊(问题2),怎样才能取了第一行接着让指针指向下一行(问题1)?
...全文
729 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
yndfcd 2007-12-19
  • 打赏
  • 举报
回复
getline使用string类型作为接收输出的参数,因此不用知道一行具体有多少个字符.

默认使用'\n'作为换行符.在读取过程中,读取指针会自动移动,当你读完一行后,指针会指向下一行的开头.
飞哥 2007-12-19
  • 打赏
  • 举报
回复
搞大点的buffer就行
ckt 2007-12-19
  • 打赏
  • 举报
回复
看看介绍

istream& getline ( istream& is, string& str, char delim );
istream& getline ( istream& is, string& str ); <string>

Get line from stream

Extracts characters from is and stores them into str until a delimitation character is found.

The delimiter character is delim for the first function version, and '\n' (newline character) for the second. The extraction also stops if the end of file is reached in is or if some other error occurs during the input operation.

If the delimiter is found, it is extracted and discarded, i.e. it is not stored and the next input operation will begin after it.

Notice that unlike the c-string versions of istream::getline, these string versions are implemented as global functions instead of members of the stream class.


Parameters
is
istream object on which the extraction operation is performed.
str
string object where the extracted content is stored.
delim
The delimiting character. The operation of extracting succesive characters is stopped when this character is read.

Return Value
The same as parameter is.
xdlly 2007-12-19
  • 打赏
  • 举报
回复
getline是读取一个字符串,长度由第二个参数给定,缺省结束标志是第三个参数,若不指明,默认为回车!


第三个参数是结束标志。通过判断是否读取了字符'\n'取第一行接着让指针指向下一行
ryfdizuo 2007-12-19
  • 打赏
  • 举报
回复

// getline with strings
#include <iostream>
#include <string>
using namespace std;

int main () {
string str;
cout << "Please enter full name: ";
getline (cin,str);
cout << "Thank you, " << str << ".\n";
}

对于文件来说,
std::ifstream infile("words.txt");
std::ofstream outfile("WordsFile.txt");
std::string line;

if(outfile)
{
std::cout << "Writing out to WordsFile.txt.\n";

for(int i = 0; i < 25; i++)
{
std::getline(infile, line, '\n'); //以'\n'标志结束,
outfile << line;
outfile << '\n';
}
}

64,642

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧