【问题标题】:Numbering Lines in a File With C++使用 C++ 对文件中的行进行编号
【发布时间】:2014-12-02 13:41:03
【问题描述】:

我编写了一个快速的 C++ 程序,它要求用户输入文本文件和输出文本文件。然后程序应该在左边距上对文件中的行进行编号。但是,我似乎无法让它正常工作,它编译得很好,但没有像它应该的那样对行进行编号。我认为这是我的逻辑错误。我对 C++ 中的文件 i/o 也不太熟悉,因为我现在只是在使用老式教科书学习它。

这是文件:

#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <cstdio>

using namespace std;

int main(void)
{int i = 0 , num = 1;
 string inputFileName;
 string outputFileName;
 string s;
 ifstream fileIn;
 ofstream fileOut;
 char ch;

 cout<<"Enter name of input file: ";
 cin>>inputFileName;
 cout<<"Enter name of output file: ";
 cin>>outputFileName;

 fileIn.open(inputFileName.data());
 fileOut.open(outputFileName.data());

 assert(fileIn.is_open() );
 assert(fileOut.is_open() );

 while (!(fileIn.eof()))
       {ch=fileIn.get();
        if (ch=='\n') num++;
           fileOut << num << "\n";
        s.insert(i,1,ch);     //insert character at position i
        i++;
       }
 fileOut << s;
 fileIn.close();
 fileOut.close();
 return 0;
}

如果有人能指出我正确的方向或给我一些建议,我将永远感激不尽。

【问题讨论】:

  • 不要断言在非调试环境中可能会合法失败的事情,例如文件未打开。在 while 循环中检查 eof 是错误的。
  • 您能否向我解释一下为什么它是错误的或提供一个链接以便我学习?

标签: c++ file-io iostream fstream


【解决方案1】:
int i = 0;
string line;
while (getline(infile, line))
{
    outfile << (i++) << " " << line << "\n";
}

【讨论】:

  • 好的,我应该把我的while循环修改成这样吗?
  • 是的,这就是我将如何实现它。比一次获得一个角色要容易得多。
  • @RemyLebeau 为什么要编辑我的答案以使其变得更糟?文件流中的 endl 会使其变慢。
  • 我同意我已经玩过它了,你的方法比我使用的方法好很多。太感谢了!你能给我的任何其他建议都会非常有帮助。
  • @NeilKirk:我没有“让它变得更糟”。 std::endl 是在 C++ 中结束一行的首选方式,而不是手动输出 "\n" 字符(这是 C 的做法)。 std::endl 并不慢,它以适合平台的方式处理输出换行符,它还允许流(如 ofstream)执行在遇到 std::endl 时刷新的缓冲。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 2013-06-06
  • 1970-01-01
  • 2018-07-25
相关资源
最近更新 更多