getline skipping first line

text file is

hello
there

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
void readFile(char[], ifstream&);
address records[numbersAdd];
int main(){
	char xml[30];
	
	cout<<"Enter file name ";
	cin.getline(xml, 30);
	ifstream read;
	
	readFile(xml, read);
	
	return 0;
	}



void readFile(char file[], ifstream& read){
	char line[100];
	
	read.open(file, ios::in);
	
	
	if(read.fail())
		cout<<"Sorry could not read";

	else{
		
		
		while (read.good()){
			read.getline(line, '\n');
			cout<<line;
			
			
			}
		
		}
	read.close();
	

	}


there

why? :(
Read this:

http://www.cplusplus.com/reference/istream/istream/getline/

The delimiter is the third parameter not the second

Nonetheless: For me the output is
hellothere
strange..how come..i eve did this read.getline(line, 100 '\n'); still no work
Last edited on
LOL. I think it is because your text file is stored in Windows format but you are compiling in *nix. Am I right?

The text file is

    "hello\r\nworld\r\n"

So your program reads each line as: "hello\r" and "world\r". (Try a file with a longer first line.)

JSYK, there is no reason you can't (and shouldn't) be using std::string to handle I/O. Also, don't loop on EOF.

1
2
3
4
5
6
7
string s;
ifstream f( filename );

while (getline( f, s ))
{
  cout << s << "\n";
}

Hope this helps.

[edit] Once you've got the data in a std::string, you can copy it to your char array in your struct.

 
strcpy( records[n].line, s.substr( 0, max_records_line_size - 1 ).c_str() );
Last edited on
ye may be...thanks btw
You can check by opening a terminal and typing

od -c foo.txt

(replace foo.txt with whatever your file is named.)
Topic archived. No new replies allowed.