check out what's wrong in this code....

#include<iostream>
#include<conio.h>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ofstream s1,s2;
string name1,name2;
s1.open("student1.txt",ios::out);
s2.open("student2.txt",ios::out);
cout<<"enter the name of student 1";
getline(cin,name1);
cout<<"enter the marks of student1:";
int mark1,mark2;
cin>>mark1;
s1<<name1<<mark1;
cout<<"enter the name of student 2";
getline(cin,name2);
cout<<"enter the marks of student2:";
cin>>mark2;
s2<<name2<<mark2;
s1.close();
s2.close();
return 0;
}



this code skips the input of 2nd student name.....why is this happening?and how can i fix this problem??
Last edited on
Don't make us guess, please. Post the error you received or explain the code's incorrect behavior and the behavior that is considered as correct. Also use code tags to post code.

Please read http://www.cplusplus.com/forum/beginner/1/ before posting.

Thank you.
My guess is it's because you close "s1" twice, but that's only a guess you should post the error you are recieving or the results you expect vs the ones you are getting.
Does the program skip a student name input?
closed account (zb0S216C)
1) You never check if the files are actually open before writing.
2) conio.h is deprecated. You don't even use it.
3) As Computergeek said, you close the same file stream twice.
4) State the errors/warnings you're receiving.
5) State the compiler you're currently using, along with your OS.

Wazzak
i am receiving no errors and no warnings.
This is what usually happens when one mixes operator >> and getline
for input. Newline leftovers from the former get in the way of the latter.

A simple solution would be to add a cin.get() call after every use of operator >> ...

1
2
3
4
5
6
7
8
9
//...

cin >> mark1; cin.get();

//...

cin >> mark2; cin.get();

//... 

A better solution would be to only use getline for input...

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>

using namespace std;

// get input as string and
// then convert it to int

int get_int()
{
    string input;

    getline(cin, input);

    stringstream buffer(input);

    int result;

    buffer >> result;

    return result;
}

int main()
{
    ofstream s1, s2;

    string name1, name2;

    int mark1, mark2;

    s1.open("student1.txt");
    s2.open("student2.txt");

    cout<<"enter the name of student 1: ";
    getline(cin,name1);

    cout<<"enter the mark of student 1: ";
    mark1 = get_int();

    cout<<"enter the name of student 2: ";
    getline(cin,name2);

    cout<<"enter the mark of student 2: ";
    mark2 = get_int();

    s1 << name1 << endl << mark1;
    s2 << name2 << endl << mark2;

    s1.close();
    s2.close();

    return 0;
}
thanks a lot m4ster r0shi...it's working now..
Topic archived. No new replies allowed.