help c++

Hi

i have a program to write and i got a sample code
all i need to do is read the first line and then stop

here is the sample code for you

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
#include <fstream>
#include <iostream>
#include <string>

using namespace std;

int main()
{
	
	const int size=50;
	char name[size];
	char name2[size],in[size]; 
	int number=0,counter=0,length=0;

	ifstream infile;
	ofstream outfile ("dataOut", ios::out);

		cout<< "Please enter file name: ";
		cin>> in;
		infile.open(in);
		
		infile>>number;
		cout<<number<<endl;
		while(infile)
		{
		infile.get(name,size,'\0');
		cout<<name;
		}}


and this is my data:
"0
Mary had a little lamb
2
h
3
u
9
Dictionary
Dictionary"

how can i stop reading the data after the first line "Mary had a little lamb"?

please help me with that
this doesnt help much i tried it but there is nothing that make sense

isnt there a simple command to stop reading after an EOL char is detected?
You can use getline function with '\n' as delimiter character!

i.e:

infile.getline ( name,size,'\n');
that doesnt work
1
2
3
4
5
6
7
8
9
	infile>>number;
		cout<<number<<endl;
		while(infile)
		{
		infile.getline(name,size,'\0');
		
		}
		cout<<name;
}


thats what i changed the code into and when i print it out that is my output

Mary had a little lamb
2
h
3
u
9
Dictionary
Dict


i need it to stop at the first line and print it out
try this

1
2
3
4
5
std::string string;

if(!infile.eof())
    getline(infile, string);
cout << string;


regards
tried

didnt work now it doesnt print anything
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main()
{
	const int size=50;
	char name[size];
	char name2[size],in[size]; 
	int number=0,counter=0,length=0;

	ifstream infile;
	ofstream outfile ("dataOut", ios::out);

	cout<< "Please enter file name: ";
	cin>> in;
	infile.open(in);
		
	infile>>number;
	cout<<number<<endl;
	if(infile) {
		infile.get(name,size,'\0');
		cout<<name;
	}
}

Your mistake was:
1
2
3
while(infile) {
	infile.get...
}

While your file contains characters, you KEEP on printing them out, line by line.
What i did is changing your WHILE into an IF, so IF your file contains characters, you print ONE line from the file.
Last edited on
Topic archived. No new replies allowed.