从文件中读取而不跳过空格

Reading from a file without skipping whitespaces

我正在尝试制作一个代码,该代码会更改文件中的一个给定单词,然后将其更改为另一个单词。该程序以一种逐字复制的方式工作,如果它是正常的单词,它只是将它写入输出文件,如果它是我需要更改的那个,它会写入我需要更改的那个。但是,我遇到了一个问题。程序没有将空格放在输入文件中的位置。我不知道这个问题的解决方案,我不知道我是否可以使用 noskipws 因为我不知道文件在哪里结束。

请记住我是一个完全的新手,我不知道事情是如何运作的。不知道标签够不够显眼,再提一下,我用的是C++

由于每次阅读单词都以空格或文件结尾结束,您可以简单地检查停止阅读的内容是文件结尾还是空格:

if ( reached the end of file ) {
  // What I have encountered is end of file 
  // My job is done
} else {
  // What I have encountered is a whitespace
  // I need to output a whitespace and back to work
}

这里的问题是如何检查eof(文件结尾)。 由于您使用的是 ifstream,所以事情会很简单。 当 ifstream 到达文件末尾(已读取所有有意义的数据)时,ifstream::eof() 函数将 return 为真。 假设您拥有的 ifstream 实例称为输入。

if ( input.eof() == true ) {
  // What I have encountered is end of file
  // My job is done
} else {
  // What I have encountered is a whitespace
  // I need to output a whitespace and back to work
}

PS : ifstream::good() 到达 eof 或发生错误时将 return false。在这里检查 input.good() == false 是否是更好的选择。

首先我建议你不要在同一个文件中读取和写入(至少在读取期间不要)因为这会使你的程序更难write/read。

其次,如果您想读取所有空格,最简单的方法是使用 getline() 读取整行。

可用于将单词从一个文件修改为另一个文件的程序如下所示:

void read_file()
{
    ifstream file_read;
    ofstream file_write;
    // File from which you read some text.
    file_read.open ("read.txt");
    // File in which you will save modified text.
    file_write.open ("write.txt");

    string line;
    // Word that you look for to modify.       
    string word_to_modify = "something";
    string word_new = "something_new";

    // You need to look in every line from input file. 
    // getLine() goes from beginning of the file to the end.
    while ( getline (file_read,line) ) {
        unsigned index = line.find(word_to_modify);
        // If there are one or more occurrence of target word.
        while (index < line.length()) {
            line.replace(index, word_to_modify.length(), word_new);
            index = line.find(word_to_modify, index + word_new.length());
        }

        cout << line << '\n';
        file_write << line + '\n';
    }


    file_read.close();
    file_write.close();
}