-3

I am making a simple program to find out the number of lines not starting with a using file handling. I am not able to understand why my loop is only running 4 times when it should clearly run 0 through 1 less than value of lines. What is the problem here?

#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;
}
MAVERICK
  • 41
  • 1
  • 9
  • "the number of lines not starting with a using file handling. " With a what? Looks like you dropped some important info there. – user4581301 Nov 05 '17 at 05:34
  • 2
    Formatted input doesn't read the end of line character. The first getline does, then the next getline actually waits for you to type. I assume that's your issue? – Retired Ninja Nov 05 '17 at 05:35
  • https://stackoverflow.com/questions/1744665/need-help-with-getline – Retired Ninja Nov 05 '17 at 05:36
  • Possible duplicate of [Need help with getline()](https://stackoverflow.com/questions/1744665/need-help-with-getline) – Retired Ninja Nov 05 '17 at 17:12

1 Answers1

0

I Think you should use ifstream to read file, and standard getline to read line from file like this :

#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;
}
mystic_coder
  • 462
  • 2
  • 10
  • Your program will have the same problem I assume the OP is having, which is dealing with the leftover whitespace and EOL character after the formatted input. – Retired Ninja Nov 05 '17 at 17:12