C++ 循环的文件处理

C++ 循环的文件处理,c++,loops,file-handling,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; ofstre

我正在做一个简单的程序来找出不以使用文件处理开始的行数。我无法理解为什么我的循环只运行了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;
}
#包括
#包括
使用名称空间std;
int main()
{
常数int s=80;
char-str[s];
整数线=0,a=0,直线=0;
ofstreamfout(“file6.txt”,ios::out);
coutlines;
对于(int i=0;ifout我认为您应该使用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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
int main()
{
std::ifstream是(“file6.txt”);
std::字符串行;
int linesToRead=0;
标准::cin>>linesToRead;
while(std::getline(is,line))
{

if(linesToRead)“使用文件处理时不以开头的行数。”使用what?看起来您在那里删除了一些重要信息。格式化输入不读取行尾字符。第一个getline读取,然后下一个getline实际等待您键入。我假设这是您的问题?您的程序可能重复会遇到与我假设OP相同的问题,即处理剩余内容格式化输入后的空格和EOL字符。