循环文件处理

时间:2017-11-05 05:24:04

标签: c++ loops file-handling

我正在编写一个简单的程序来查找不使用文件处理的行数。我无法理解为什么我的循环只运行4次,它应该明显地运行0到1小于行的值。这有什么问题?

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
     const int s = 80;
     char str[s];
     int lines = 0, a = 0, alines = 0;
     ofstream fout("file6.txt", ios::out);
     cout<<"Enter the number of lines you want to enter: ";
     cin>>lines;
     for(int i = 0; i < lines; i++)
     {
          cin.getline(str, 80);
          fout<<str<<endl;
     }
     return 0;
}

1 个答案:

答案 0 :(得分:0)

我认为您应该使用ifstream来读取文件,使用标准的getline来读取文件中的行,如下所示:

#include <iostream>
#include <vector>
#include <queue>
#include <string>
#include <cmath>
#include <sstream>
#include <fstream>


int main()
{
    std::ifstream is("file6.txt");
    std::string line;

    int linesToRead = 0;

    std::cin>>linesToRead;

    while(std::getline(is, line))
    {
        if(linesToRead <= 0)
            break;
        std::cout<<line<<std::endl;
        --linesToRead;
    }
    return 0;
}