从文件中读取行 - 删除多余的空格

Reading lines from a file -- removing extra spaces

本文关键字:删除 多余 空格 文件 读取      更新时间:2023-10-16

我正在使用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。这与新线路有关吗?如果是这样,如何从文件正确提取这些单词?

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

在 linux 中,通常的行尾是"\r",实际上是两个字符。我不完全确定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

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

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