Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/148.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 简单文件I/O程序C++; #包括 #包括 #包括 #包括 使用名称空间std; int main(){ 系统(“cls”); 字符线[75]; int lc=0; ofstreamfout(“out.txt”,ios::out); ifstream-fin(“data.txt”,ios::in); 如果(!fin){ cerr_C++_C++11_File Io_While Loop_Codelite - Fatal编程技术网

C++ 简单文件I/O程序C++; #包括 #包括 #包括 #包括 使用名称空间std; int main(){ 系统(“cls”); 字符线[75]; int lc=0; ofstreamfout(“out.txt”,ios::out); ifstream-fin(“data.txt”,ios::in); 如果(!fin){ cerr

C++ 简单文件I/O程序C++; #包括 #包括 #包括 #包括 使用名称空间std; int main(){ 系统(“cls”); 字符线[75]; int lc=0; ofstreamfout(“out.txt”,ios::out); ifstream-fin(“data.txt”,ios::in); 如果(!fin){ cerr,c++,c++11,file-io,while-loop,codelite,C++,C++11,File Io,While Loop,Codelite,如果文件中的任何一次尝试读取长度超过74个字符,getline将为fin设置failbit,您将永远无法到达文件的结尾。请将代码更改为以下内容: #include <iostream> #include <fstream> #include <stdlib.h> #include <process.h> using namespace std; int main(){ system("cls"); char mline[75];

如果文件中的任何一次尝试读取长度超过74个字符,
getline
将为
fin
设置
failbit
,您将永远无法到达文件的结尾。请将代码更改为以下内容:

#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <process.h>
using namespace std;

int main(){
    system("cls");
    char mline[75];
    int lc=0;
    ofstream fout("out.txt",ios::out);
    ifstream fin("data.txt",ios::in);
    if(!fin){
        cerr<<"Failed to open file !";
        exit(1);
    }
    while(1){
        fin.getline(mline,75,'.');
        if(fin.eof()){break;}
        lc++;
        fout<<lc<<". "<<mline<<"\n";
    }
    fin.close();
    fout.close();
    cout<<"Output "<<lc<<" records"<<endl;
    return 0;
}

至少发布可以编译的代码!:-)它确实在CodeLite(g++)上编译。然后CodeLite有严重缺陷:
而(1)){
是无效的语法。你能解释一下吗?(我几乎是个编程新手)你有一个左括号,但有两个右括号。之前的错误已经解决了(通过进行您建议的更改)。但是,我打开了输出文件,但它是空的!对我来说效果很好,可能有什么东西阻止了对您的输出文件的访问。@Monk您不能仅从mline输出…它不能保证以NUL终止…您应该使用
fout.write(mline,fin.gcount());
@TonyD最多读取count-1个字符,然后附加一个空字符。@user657267:啊,是的-我会回去睡觉……对不起。如果(!fout)添加一个
,可能会更好…
尽管检查-可能它没有正确打开-也会丢失
out
参数-
会处理这个问题。在原始代码中,最后一行不会被写入,因为
eof()
输入后和输出前的测试-你还没有这样做吗?
for (; fin; ++lc) {
  fin.getline(mline,75,'.');
  if (!fin.eof() && !fin.bad())
    fin.clear();
  fout<<lc<<". "<<mline<<"\n";
}
#include <iostream>
#include <fstream>
#include <string>

int main()
{
  int lc = 0;
  std::ofstream fout("out.txt");
  std::ifstream fin("data.txt");

  for (std::string line; getline(fin, line, '.'); )
    fout << ++lc << ". " << line << "\n";

  std::cout << "Output " << lc << " records\n";
}