.txt文件末尾的换行影响输出

时间:2019-10-28 12:55:43

标签: c++ logic newline fstream

任务:

转换文本以在记录周围添加符号。

问题:

源文件末尾的新行会影响输出,因此最后一条记录将保存两次。我找不到逻辑错误。

我尝试在ignnore中添加if语句: “”,“”,“ \ n”,“ \ 0” 我找不到逻辑错误。

bool Converter::ReadFile(std::string _filename) //filename given from the call
{
    std::string element = ""; //temp variable for one element for the text file

    std::ifstream reader(_filename + ".txt"); //open a stream to read the file

    if (reader.fail()) //check if the file is readable (also for checking if it exists)
    {
        //couldnt read file
        return false;
    }
    else //if it is readable ->
    {
        do { //loop till end of file
            if (reader.is_open())
            {
                reader >> element; //take one element
                if ((element != "") && (element != " ") && (element != "\n") && (element != "\0")) //My attempt to ignore all kinds of new lines
                {
                    SaveInCache(element); //if it doesnt contain any of the characters above save it in a vector
                }
            }
        } while (reader.eof() == false);
        reader.close(); //after reaching the end of file close the stream
        return true;//reading successful
    }
}

它是一个简单的控制台应用程序,应从.txt文件中读取文本并将其写入以下格式的新文件中:

'element1',\ n

'element2',\ n

'element3',\ n

'element4'

最后一个元素应该是:

“元素”

但是,源文件末尾会有新行,如下所示:

'element1',\ n

'element2',\ n

'element3',\ n

'element4',\ n

'element4'

0 个答案:

没有答案