当使用getline时,哪种方式更好

which way is better when using getline?

本文关键字:方式 更好 getline      更新时间:2023-10-16

从文件中读取时,我们有两种方法

方式1:

ifstream fin("data.txt"); 
const int LINE_LENGTH = 100; 
char str[LINE_LENGTH];  
while( fin.getline(str,LINE_LENGTH) )
{    
    cout << "Read from file: " << str << endl;
}

方式2:

ifstream fin("data.txt");  
string s;  
while( getline(fin,s) )
{    
    cout << "Read from file: " << s << endl; 
}

哪个更好?就我个人而言,我更喜欢方式2,因为我不需要指定最大长度,你的意见是什么?

方法2更好(更习惯,避免可能破坏解析的硬编码长度)。我想写得稍微不一样:

for(string s; getline(fin,s); )
{    
    cout << "Read from file: " << s << endl; 
}

std::getlineistream::getline来自不同的接口,接受不同类型的参数

特别是对于您的情况,我同意使用std::getline(fin,s)更方便。