【问题标题】:Reading lines from a file -- removing extra spaces从文件中读取行 - 删除多余的空格
【发布时间】:2014-02-27 15:59:46
【问题描述】:

我正在使用ifstream 从文件中获取行并将它们存储到字符串中。每行包含一个没有空格的单词。

    virtual void readFromFile(char* input){
        ifstream inf(input);

        if(!inf){
            cerr << "The specified file could not be found." << endl;
        }

        while(inf){
            string str;
            getline(inf, str);
            pushFront(str); // store it in my data structure

        }

        inf.close();
    }

文件.txt

a <= returns length 1 (correct)
at <= returns length 3
ate <= returns length 4
rate <= returns length 5
irate <= returns length 6

当我在与文件开头对应的字符串上调用length() 时,它会返回正确的值。但是,在与所有其他行对应的字符串上调用 length 会导致偏移量为 +1。例如,如果字符串的长度实际上是 5,则返回 6。这是否与换行有关?如果是这样,我怎样才能正确地从文件中提取这些单词?

【问题讨论】:

  • 你确定行上没有写间隔吗?这可能与 Linux 系统用于新行 '\r' 和 '\n' 的两个符号有关,但我认为 getline 会修剪它们。即便如此,请尝试看看错误的单词是否以'\r'或'\n'结尾,我们肯定会知道。
  • 让我看看。
  • 我觉得不错? oi61.tinypic.com/99qqsz.jpg
  • 这是Linux。可能会假设某些行以 linux 行结尾“\r\n”结尾。它们必须是这样的,否则您将无法获得只有 36 个可见字符的 55 个字符。然而,显然,第一行仅以 '\n' 结尾,这就是为什么那里没有不匹配的原因。尝试将输入的最后一个字符设置为 '\0' 以防它匹配 '\r' 我认为这可能会解决它。
  • 为了看到 vim 中的不可见字符,请执行 :set list。这将帮助您弄清楚发生了什么

标签: c++ ifstream


【解决方案1】:

您正在使用 vi 作为文本编辑器,因此您可以通过执行 :set list 来显示不可见字符。这将帮助您弄清楚您在大多数行中看到的这些额外字符可能是什么。

在 linux 中,通常的行尾是“\r\n”,实际上是两个字符。我不确定getline 是否会同时忽略它们。但是,作为预防措施,您可以添加以下逻辑:

getline(inf, str);
int len = str.size();
if (str[len - 1] == '\r') {
   str.pop_back(); // not C++11 you do it str = str.erase(str.end() - 1);
}
pushFront(str); // store it in my data structure

【讨论】:

【解决方案2】:

如果您的文本文件中定义了格式,则每一行都只包含一个单词,因此阅读这些单词更容易也更确定。

void readFromFile(char* input){
    ifstream inf(input);
    if(!inf){
        cerr << "The specified file could not be found." << endl;
    }
    for( string word; inf >> word; )
        pushFront( word ); // store it in my data structure
}   // inf.close() is done automaticly leaving the scope

【讨论】:

    猜你喜欢
    • 2014-08-07
    • 2018-04-09
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2015-07-17
    相关资源
    最近更新 更多