Click here to Skip to main content
15,936,709 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C++
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
void main()
{
clrscr();
ifstream g;
char str[100];
g.open("a.txt");
while(str!='\n') problem is here
{
g.getline(str,20);
cout<<str;
}
g.close();
getch();
}


I read that getline functions reads a seqpence of character untill end of line is reached('\n')
but my program can not work
Posted
Comments
CHill60 12-Jun-13 7:30am    
When you say "my program can not work" give us details of either the error message(s) you are getting or explain how the actual results differ from your expected results. Use the Improve question link above to update your post

I have modified your program for you, here is the code:

C++
#include <iostream>
#include <fstream>

using namespace std;

int main()
{

	ifstream g;

	char str[100];

	g.open("a.txt");

        /* repeat following actions 
           until end of file is reached */

	while( ! g.eof() ) 
	{
                /* clear our string, so we can get
                   new data */

		memset( &str, '\0', sizeof(str) );
		
                // get 100 characters into str
	
		g.getline(str,100);

                // write the result, and go to new line

		cout<<str<<endl;
		
	}

	g.close();

	return 0;
}


It has been a while since I have dealt with this, but I hope that this will help you.
Best regards and good luck!
 
Share this answer
 
v3
Quote:
my program can not work

No it cannot.
There is never going to be a point where str a pointer to 100 chars is going to be equal to the constant value '\n' which if I remember correctly is evaluated as 13.
Your while loop will never complete. Your while loop is also possibly unnecessary if you only want to read one line but I don't know for sure what you're trying to do.

I would recommend you check your understanding of pointers. Many people find this a difficult topic in C/C++.
 
Share this answer
 
Comments
MyOldAccount 18-Sep-13 12:36pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900