[英]Read last empty line of a text file in C++
我试试
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<string> readLines(string filename)
{
ifstream infile(filename);
vector<string> v;
string line;
bool good;
do {
good = getline(infile, line).good();
if (!good) break; //<---- if exists, or not - is bad
v.push_back(line);
} while (good);
return v;
}
int main() {
auto v = readLines("test.txt");
for (auto &line:v)
cout << ">" << line << endl;
}
如果我中断循环,则向量中没有最后一行,如果没有中断-尽管不在文件中,但添加空行。 我想用测试文件进行精确测试,如果存在最后一个空行很重要。
解决方法很简单:
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
vector<string> readLines(string filename)
{
ifstream infile(filename);
vector<string> v;
string line;
bool readedNewline;
if (infile.peek() != EOF)
while(true) {
readedNewline = getline(infile, line).good();
v.push_back(line);
if (!readedNewline) break;
}
return v;
}
int main() {
auto v = readLines("test.txt");
for (auto &line:v)
cout << ">" << line << endl;
}
getline().good() 如果后行是换行符,则返回 true。 最后推送到向量不好(),因此我必须检查文件是否为空(peek())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.