当使用getline时,哪种方式更好
which way is better when using getline?
从文件中读取时,我们有两种方法
方式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::getline和istream::getline来自不同的接口,接受不同类型的参数
特别是对于您的情况,我同意使用std::getline(fin,s)更方便。
相关文章:
- C++:将控制台输出存储在宏中更好吗
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 初始化具有非默认构造函数的std::数组项的更好方法
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 为什么新的随机库比std::rand()更好
- 寻找一种更好的方法来表示无符号字符数组
- 哪种方法更好,性能明智
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 什么是更好的做法?通过指针或标识符传递类成员?
- 寻求更好地理解标准::访问
- 哪种方式将 HHOOK 消息返回到系统更好
- 以编程方式检测按键的更好方法
- 哪种方式更好地获得64位整数中较低的32位
- 比如果其他更好的方式..用于线性插值
- 当使用getline时,哪种方式更好
- 字符串操作-需要更好的方式
- 更好的是,或在不同的方式编码类似的函数的优势
- 3D模型移动,找到一个更好的方式来移动3D模型
- c++ OOP哪一种方式给构造函数赋值更好
- 在cuda中有更好/更干净/更优雅的malloc和free方式吗?