LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Mobile (http://www.linuxquestions.org/questions/linux-mobile-81/)
-   -   small doubt in filehandling (http://www.linuxquestions.org/questions/linux-mobile-81/small-doubt-in-filehandling-4175428623/)

priya sweet 09-23-2012 05:19 AM

small doubt in filehandling
 
hello everyone
please help me with the following code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream fin;
fin.open("data", ios:: out);
string str;
cin >> str;
fin << str;
fin.close();
fin.open("data", ios::in);
while(fin) {
fin.get(ch);
cout << ch;
}
return 0;
}

if the input is : priya
the output should be priya
but my code is showing the output as priyaa
please help me to sort out the problem with the above code

konsolebox 09-23-2012 05:51 AM

Perhaps you mean this:
Code:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    fstream fin;
    fin.open("data", ios:: out);
    string str;
    cin >> str;
    fin << str;
    fin.close();
    fin.open("data", ios::in);
    char ch;
    while (fin.get(ch)) {
        cout << ch;
    }
    fin.close();

    return 0;
}


priya sweet 09-23-2012 06:20 AM

ohh thank you so much . Now its working properly. But will you please say me what is the difference. And also have a look at this code

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream fin, fin1;
fin.open("copy", ios :: out );

int n;
string str;
cout << "enter no of lines" << endl;
cin >> n;
int i = 0;

do {
getline( cin, str );
fin << str << endl;
i++;
}

while ( i < n );

fin.close();
return 0;
}
In this code i am entering 5 lines but it is taking only 4 lines as input. can u please help me in this case also.what is my wrong here??

konsolebox 09-23-2012 08:05 AM

I'm not sure why that happens but as a workaround, you could flush input with ignore() before reading again:
Code:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
        fstream fin, fout;

        fout.open("copy", ios::out);

        int n;
        string str;

        cout << "enter no of lines" << endl;

        cin >> n;
        cin.ignore();

        for (int i = n; i > 0; --i)
        {
                getline(cin, str);
                fout << str << endl;
        }

        fout.close();

        fin.open("copy", ios::in);

        while (cout << fin.rdbuf())
                ;

        fin.close();

        return 0;
}


priya sweet 09-23-2012 08:56 AM

thank you so much. My doubt is cleared.


All times are GMT -5. The time now is 03:40 PM.