// getlineDemo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
/*
* Note:
这里需要区分 getline和 std::cin.getline,是属不同的二个类中的函数,行参不一样,但功能是差不多的
一, getline(cin,str)是string类对象的成员函数,即string::getline,使用时需头文件#include <string>,例子:1,2,4
declaration:
(1) istream& getline (istream& is, string& str, char delim);
(2) istream& getline (istream& is, string& str);
二, cin.getline是输入流对象的成员函数,即istream::getline,头文件#include<iostream> ,例子:3
cin.getline
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
*/
const char* g_fileName = "file.txt";
bool creatFile()
{
std::ofstream ofstr( g_fileName );
if ( !ofstr )
return false;
std::stringstream ss;
ss<<"this is the first line \n";
ss<<"this is the second line \n";
ss<<"this is the third line \n";
ofstr << ss.str();
ofstr.close();
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
// 1, 读取一个流串到string中,设置停止条件
std::stringstream ss;
ss << "abcdefgh";
std::string tempStr = "";
getline( ss, tempStr, 'd' ); // or like this: getline( std::cin, tempStr, 'd' )
std::cout << "处理前的字符串:" << ss.str() << ", getline处理遇'd'之后的字符串:" << tempStr << std::endl;
// 2, 读取一个流串到string中,没有设置停止条件
ss.seekg( std::ios_base::beg ); // or: ss.seekg(0, ss.beg );
tempStr.clear();
getline( ss, tempStr ); // or like this: getline( std::cin, tempStr, 'd' )
std::cout << "处理前的字符串:" << ss.str() << ", getline读取整行的字符串:" << tempStr << std::endl;
// 3,读取一个流串到char数组
ss.seekg( std::ios_base::beg );
char charArr[16] = {0};
std::cout << "请输入一个中间带'd'的字符串:";
std::cin.getline( charArr, 16, 'd' );
std::cout << "通过cin.getline的方式过滤带'd'的字符串之后的内容:" << charArr << std::endl;
// 4,getline循环读取文件中的每一行内容
if ( !creatFile() )
return -1;
std::ifstream ifstr( g_fileName );
if ( !ifstr )
return -1;
unsigned int lineNum = 1;
while( getline( ifstr, tempStr ))
{
std::cout << " LineNum: " << lineNum << " , contens: " << tempStr << std::endl;
++lineNum;
tempStr.clear();
}
ifstr.close();
system("pause");
return 0;
}
getline函数使用总结
最新推荐文章于 2023-02-05 21:55:57 发布