c++ - 使用getline时哪种方式更好?

标签 c++ c++11

<分区>

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

方式一:

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;
}

方式二:

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

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

最佳答案

方法 2 更好(更惯用,避免了可能破坏解析的硬编码长度)。我会稍微不同地写它:

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

关于c++ - 使用getline时哪种方式更好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25374007/

相关文章:

c++ - 关于忽略字符顺序的字符串哈希函数的建议

c++ - 比较 boost 功能 - 功能签名?

c++ - g++:静态链接不起作用

c++ - 如何在编译时计算梅森数

c++ - union 实例的默认初始化有什么影响?

使用较小内存量时出现 C++ std::bad_alloc 错误?

c++ - 在模板化函数中使用 unique_ptr<int[]>、vector<int> 和 int[]

c++ - 为什么这个线程不知道它是谁?

c++ - 多文件项目中的全局函数?

c++ - 使用类似策略模式的文件解析器 - 如何获得结果?