C++ 重写一个文件,但在一个词之前遗漏了所有内容

标签 c++ visual-c++

我正在使用 Visual C++ Express 2010...而且我对 C++ 还很陌生。

我想读取一个文件,然后删除单词“<--START-->”之前的所有内容,然后用其余部分重写该文件。

这是我到目前为止读取文件的代码:

#include "stdafx.h"
#include <iostream>
#include <fstream>

using namespace std;

int main() {
  ifstream myReadFile;
  myReadFile.open("text.txt");
  char output[500];
  int found;
  int line;
  if (myReadFile.is_open()) {
    line = 0;
 while (!myReadFile.eof()) {
     myReadFile >> output;
     if(line > 20) {
         cout << output;
     }
     line++;
 }
}
myReadFile.close();
system("PAUSE");
return 0;
}

非常感谢。

最佳答案

首先,您的while 循环是错误的。事实上,这样的 while 循环几乎总是错误的。

你应该把循环写成:

while (myReadFile >> output) 
{
     if (line > 20) {
         cout << output;
     }
     line++;
}

您的 while(!myReadFile.eof()) 循环是错误的,因为 eof 标志(或任何其他失败标志)在之后设置 尝试从流中读取失败;这意味着,如果读取尝试失败,您仍在输出,因为您仍在循环中,并且循环中的其余代码仍在执行,而实际上它不应该执行。

但是,在我的版本中,如果尝试读取(即 myReadFile >> 输出)失败,则返回 std::istream& 隐式 转换为 false,循环立即退出。如果它没有失败,返回的流隐式转换为true

顺便说一句,在我看来,您想逐行阅读,而不是逐字阅读。如果是这样,那么你应该这样写:

std::string sline; //this should be std::string
while (std::getline(myReadFile, sline))
{
     if (line > 20) {
         cout << sline;
     }
     line++;
}

再次 std::getline返回 std::istream。如果读取成功,返回的流隐式转换为true并且循环将继续,或者如果不成功,那么它将隐式转换为 false 并且循环将退出。

关于C++ 重写一个文件,但在一个词之前遗漏了所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6404352/

相关文章:

c++ - SDL、标题和奇怪的错误..?

c++ - 编写此代码的正确方法是什么?

c++ - char[] 上的一元运算符

c++ - boost lexical_cast<std::string>(int) MSVC 2008 错误

c++ - 为什么要调用基础构造函数?

c++ - 如何在 Linux 中的 GDB/Nemiver 中显示 C++ STL 容器

c++ - 我可以使用 std::realloc 来防止冗余内存分配吗?

C++ windows位图绘制文字

c++ - 从派生类和基类调用函数

c++ - 函数模板和 "normal"函数奇怪的不一致