【问题标题】:How do I deal with a carriage return line feed when trying to read in file尝试读取文件时如何处理回车换行
【发布时间】:2018-08-03 01:48:27
【问题描述】:

所以我正在处理一个需要读取的文件,其中包含逗号分隔单词和每行末尾的回车换行符,但我无法找到处理它的方法。我正在尝试在逗号之前读取每个单词并将其放入 a 向量中,直到它到达回车换行符,但我遇到了问题。

这是我的文本文件(在notepad++上可以看到符号。在实际文本中,[]里面的东西没有出现)

microwave,lamp,guitar,couch,bed,dog,cat[cr][lf]
P1:microwave,couch,bed,dog,chair,bookcase,fish[cr][lf]

我尝试了多种解决方案,但似乎没有任何效果。这是我到目前为止所尝试的。但它显然不起作用。我看到一些用户建议使用 substring 以某种方式读出逗号,并读入单词,但我不知道该怎么做。我找不到一个好的教程或示例。在我的脑海中,我有算法(或至少,如何去执行它的步骤),但我不确定如何去实现它。

Import file (istream)

Read until comma, take string and place it in vector1 (getline, input, ,), vector.push_back(input)
Repeat previous step until you reach \cr\lf stop reading. (getline(input, '/r'))

move on to the next line
Read until comma, take string and place it in vector2
Repeat
Read the line until /cr/lf

这是我使用上述部分步骤实践的代码。

string input;

    vector<string> v1;
    vector<string> v2;


    ifstream infile;

    infile.open("example.txt");

    while(getline(infile, input)) //read until end of line
    {
        while(getline(infile, input, '\r')) //read until it reaches a carriage return
        {
            while(getline(infile, input, ',')) // read until it reaches a comma
            {
                v1.push_back(input);  //take the word and put in vector.

            } 

        }

    }

    infile.close();

任何帮助将不胜感激。

编辑:我忘了提。当我使用这段代码时,它似乎没有将任何东西导入向量中。我确信所有单词都在 getline 函数的某个地方丢失了,但我不知道如何在不使用它的情况下只读取逗号和回车换行符。

【问题讨论】:

  • 您不必担心 \cr\lf 对,因为 Windows 应该会自动将它们转换为单个 \r。因此std::getline 应该做正确的事。只关心行和逗号。
  • @Galik — 对,但 ’\r’ 是一个错字。应该是’\n’,即换行符。
  • @PeteBecker 它匹配代码中的 cmets :) \r 是回车符,\n 是换行符。

标签: c++ string vector getline


【解决方案1】:

您应该先使用getline() 获取整行。它应该为您处理回车。然后,将结果放入stringstream 并在其上使用getline() 分隔逗号处的行。

我将输入读入向量向量的代码:

#include <fstream>
#include <iostream>
#include <sstream>
#include <vector>

int main()
{
    std::ifstream fin("input.txt");
    std::vector<std::vector<std::string>> result;
    for(std::string line; std::getline(fin, line);)
    {
        result.emplace_back();
        std::stringstream ss(line);
        for(std::string word; std::getline(ss, word, ',');)
        {
            result.back().push_back(word);
        }
    }
    for(const auto &i : result)
    {
        for(const auto &j : i)
        {
            std::cout << j << ' ';
        }
        std::cout << '\n';
    }
}

您可以修改它以读取两个向量,只需删除外部循环并为两个向量/行中的每一个使用两个单独的循环。

在您的代码中,您首先有一个循环逐行读取,直到文件末尾。在你读完一行之后,你有一个循环,直到一个 '\r',据我所知,这不会出现在一个普通的文本文件中。即使文件中有'\r',你也会覆盖你刚刚从外循环读入的内容。里面的循环也一样。

您是否听说过 while(getline(fin, str)) 在不知道文件如何工作的情况下读取文件?

【讨论】:

  • 我同意,但是为了公平起见,人们有时会遇到问题,当他们有一个在 Windows 上编写的文本文件并尝试在 UNIX 系统上读取它时。如果只是简单地复制它,而没有进行适当的格式转换,它们最终会得到杂散的 CR 值,并将它们误解为 '\r'(因为为方便起见,'\r' 通常具有与 CR 相同的 )。
猜你喜欢
  • 2017-03-24
  • 1970-01-01
  • 2019-12-20
  • 1970-01-01
  • 1970-01-01
  • 2015-11-11
  • 2018-04-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多