Pregunta

I am trying to increment the variable int lines everytime getline encounters a '\n' character in an input file. However, my variable isn't being incremented after a new line and I'm assuming maybe I'm not checking the buffer correctly that I'm loading the characters of the line into. Here is my code with much of it simplified:

int lines = 0;
while(input.getline(buffer, 100))
{

if(buffer[0] == '\n')
   lines++;
}

File format(I want it to increment once it encounters the '\n' between the two lines of data):

20012 CSCI 109 04 90 1 25

-- ID days_constraint start_contraint 

Thanks guys.

¿Fue útil?

Solución

if(buffer[0] == '\n')

That will only work if the newline is the first character in the line, i.e. if it's a blank line. So you're only counting blank lines. It should have been:

if(buffer[strlen(buffer)] == '\n')

But as @DavidSchwartz points out, you don't need it at all.

Otros consejos

Assume you used std::basic_istream::getline, you don't need the check whether '\n' in your buffer, because '\n' was used as the delimiter. So just increment every successful getline is OK.

int lines = 0;
while(input.getline(buffer, 100))
{
   lines++;
}
//other handle exception logic
if (input.fail()
{
// lines number is not valid
}
if (input.bad())
{
//......
}

Assume file is valid and lines less than 100, or you should add exception handle logic.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top