[英]Detecting newline characters inFile stream c++
确定使用ifstream从纯文本文件中读取数据时何时到达数据行末尾的最简单(最简单)方法是什么? 基本上,我需要根据数据在文本文件中的位置(以行号衡量)对数据执行不同的操作。
因此,如果我有一个包含以下内容的文本文件:
12 54 873 9 87 23
34 25 93 10 94 5 8
我可能要存储第一行,但是在存储,丢弃或执行其他操作之前,我需要修改第二行。
直接的文件读取看起来像这样
while (inFile >> temp)
//store temp;
编辑:
我还没有测试过,这是我想出的。 我没有对复杂的字符串类函数做很多事情,因此我的语法可能不正确,但是看起来我走对了吗?
// include the necessary libraries
string line, delim = ' ';
ifstream inFile;
int temp, lineNum = 1;
size_t pos = 0;
file.open('/path/to/file');
while(getline(file, line)){
while ((pos = line.find(delim)) != npos) {
temp = file.substr(0, file.find(delim);
line.erase(0, pos + delim.length());
// depending on the value of lineNum
// work with temp
}
lineNum++;
}
一个快速的问题是,当我直接将其分配给temp时,它是否可以转换为int
(我需要什么),或者在使用它之前是否需要将其转换为int。
拥有要打开的文件后,可以使用getline()
string line;
ifstream file;
file.open('/path/to/file');
while(!file.eof()){
// delimiter by default is '\n'
getline(file, line);
cout << line << endl;
}
尝试这样的事情:
std::ifstream inFile("/path/to/file");
std::string line;
int lineNum = 0;
while (std::getline(inFile, line))
{
++lineNum;
std::istreamstream iss(line);
int value;
while (iss >> value)
{
// work with value depending on lineNum
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.