【问题标题】:Detecting newline characters inFile stream c++检测文件流c ++中的换行符
【发布时间】:2014-11-12 20:42:43
【问题描述】:

在使用 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 成字符串'line',把'line' 放入字符串流并处理
  • file.substr() 应该是 line.substr()file.find() 应该是 line.find()。但是你已经有了pos,所以第二个find() 是多余的。为了使解析更容易,您应该使用istringstream 来解析每一行。然后,您可以使用带有分隔符的getline() 从流中读取分隔的子字符串,或者在分隔符为空白时使用流的>> 运算符。我编辑了我的答案以表明这一点。

标签: c++ newline fstream


【解决方案1】:

一旦你有了想要打开的文件,你就可以使用 getline()

string line;
ifstream file;
file.open('/path/to/file');
while(!file.eof()){
    // delimiter by default is '\n'
    getline(file, line);
    cout << line << endl;
}

【讨论】:

  • 你不应该使用while(!file.eof())
  • 这只是一个简单的例子。如果我可能会问,为什么不使用 eof()? (除了文件末尾有一堆空行的可能性)。
  • 仍然错误:对 EOF 的测试是错误的(在某些情况下是合理的)并且省略了对提取的测试(getline)
  • 如果我需要处理每行的单个数字/整数怎么办?
  • @user3776749 将实际的输入运算符放入参数中。 std::getline()operator&gt;&gt;() 之类的函数将返回流,并将其转换为布尔值,根据成功输入返回 true 或 false。
【解决方案2】:

试试这样的:

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

【讨论】:

  • 我想出了一些类似的东西,请参阅编辑以获取更新。
  • 这看起来很有希望,我会报告它是否正常运行;感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 2014-01-08
  • 2010-09-07
相关资源
最近更新 更多