C++ 从文件中读取行--删除额外的空格

C++ 从文件中读取行--删除额外的空格,c++,ifstream,C++,Ifstream,我使用ifstream从文件中获取行并将它们存储到字符串中。每行包含一个不带空格的单词 virtual void readFromFile(char* input){ ifstream inf(input); if(!inf){ cerr << "The specified file could not be found." << endl; } while(inf){

我使用
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();
    }
virtualvoid readFromFile(char*input){
ifstream-inf(输入);
如果(!inf){

cerr您正在使用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

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

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
void readFromFile(char*input){
ifstream-inf(输入);
如果(!inf){
cerr单词;)
pushFront(word);//将其存储在我的数据结构中
}//inf.close()自动完成,离开作用域

您确定行上没有写间隔吗?这可能与Linux系统用于新行“\r”和“\n”的两个符号有关,但我认为getline会将这两个符号都修剪掉。即使如此,请尝试查看错误的单词是否以“\r”或“\n”结尾,我们肯定会知道。让我检查一下。看起来不错吗?Th是linux。可能假定某些行以linux行结尾“\r\n”。它们必须是这样的,否则您将无法获得只有36个可见字符的55个字符。但是,显然,第一行仅以“\n”结尾,这就是为什么没有不匹配的原因。尝试将输入的最后一个字符设置为“\0”,以防它与“\r”匹配。我认为这可能会修复它。为了在vim do
中查看不可见字符:设置list
。这将帮助您了解发生了什么。我认为最好链接到一些或。
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