2016-11-22 91 views
0

我试图做一个代码,它会改变文件中的给定单词,并将其更改为另一个单词。该程序的工作方式是逐字复制,如果它是正常的话,它只是将它写入输出文件,如果它是我需要更改它的那一个,写入我需要更改的那个。但是,我已经遇到了一个问题。程序不会将空格放入输入文件中。我不知道这个问题的解决方案,我不知道我是否可以使用noskipws,因为我不知道文件在哪里结束。从文件中读取而不跳过空格

请记住我是一个完整的新手,我不知道事情是如何工作的。我不知道标签是否足够明显,所以我会再次提及我使用C++

+0

看到输入修改['noskipws'](http://en.cppreference.com/w/CPP/IO/MANIP/skipws)。 –

+1

显然,你*知道你何时到达文件结尾:读取另一个字符或单词的尝试失败。 –

+0

当我使用'noskipws'时,'eof()'不起作用。但我想我不应该用它来检查文件是否已经结束 –

回答

0

由于每个单词的读取都以空格或文件结尾结束,因此您可以简单地检查是否停止您的阅读是文件结尾或其他空白:

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()函数将返回true。 假设您拥有的ifstream实例称为输入。 PS:ifstream :: good()在到达eof或发生错误时将返回false。检查input.good()== false是否可以是更好的选择。

+0

建议使用“if(!input)”而不是“if(input.eof()== true)”进行测试,因为流中的错误多于文件尾。只需测试EOF就可以让代码进入无限循环的不良读取。 – user4581301

+0

我怎么知道它是空白还是换行符? –

+0

检查输入比eof()好,和good()相同。虽然使用ifstream作为条件可能会让初学者感到困惑。 – felix

0

首先,我建议你不要在相同的文件中读取和写入(至少在读取过程中不要读写),因为这会让你的程序更难写入/读取。

其次,如果你想阅读所有的空格,最简单的方法是用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(); 
} 
相关问题