c++ - which way is better when using getline? -
when reading file, have 2 ways
way 1:
ifstream fin("data.txt"); const int line_length = 100; char str[line_length]; while( fin.getline(str,line_length) ) { cout << "read file: " << str << endl; } way 2:
ifstream fin("data.txt"); string s; while( getline(fin,s) ) { cout << "read file: " << s << endl; } which better? personlly, prefer way2 since don't need specify max length, what's comments?
way 2 better (more idiomatic, avoids hard-coded lengths break parsing). i'd write differently:
for(string s; getline(fin,s); ) { cout << "read file: " << s << endl; }
Comments
Post a Comment