【问题标题】:file handling for loop循环文件处理
【发布时间】:2018-04-17 12:35:39
【问题描述】:

我正在制作一个简单的程序来找出不以 using 文件处理开头的行数。我无法理解为什么我的循环只运行了 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;
}

【问题讨论】:

标签: c++ loops file-handling


【解决方案1】:

我认为您应该使用 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;
}

【讨论】:

  • 您的程序会遇到与我假设 OP 相同的问题,即在格式化输入后处理剩余的空格和 EOL 字符。
猜你喜欢
  • 1970-01-01
  • 2022-10-21
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
相关资源
最近更新 更多