tags:

views:

157

answers:

3

Hi guys, i have a little problem on writing the string into a file, How can i write the string into the file and able to view it as ascii text? because i am able to do that when i set the default value for str but not when i enter a str data Thanks.

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main()
{
    fstream out("G://Test.txt");

    if(!out) {
        cout << "Cannot open output file.\n";
        return 1;
    }
    char str[200];
    cout << "Enter Customers data seperate by tab\n";
    cin >> str;
    cin.ignore();
    out.write(str, strlen(str));
    out.seekp(0 ,ios::end);
    out.close();

    return 0;
}
+8  A: 

Please use std::string:

#include <string>

std::string str;
std::getline(cin, str);
cout << str;

I'm not sure what the exact problem in your case was, but >> only reads up to the first separator (which is whitespace); getline will read the entire line.

Pavel Minaev
Definately worth noting that << and >> with strings behave differently in relation to White Space. +1
Martin York
+1  A: 

Just note that >> operator will read 1 word.

std::string   word;
std::cin >> word;  // reads one space seporated word.
                   // Ignores any initial space. Then read
                   // into 'word' all character upto (but not including)
                   // the first space character (the space is gone.

// Note. Space => White Space (' ', '\t', '\v'  etc...)
Martin York
+1  A: 

You're working at the wrong level of abstraction. Also, there is no need to seekp to the end of the file before closing the file.

You want to read a string and write a string. As Pavel Minaev has said, this is directly supported via std::string and std::fstream:

#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::ofstream out("G:\\Test.txt");

    if(!out) {
        std::cout << "Cannot open output file.\n";
        return 1;
    }

    std::cout << "Enter Customer's data seperated by tab\n";
    std::string buffer;
    std::getline(std::cin, buffer);
    out << buffer;

    return 0;
}

If you want to write C, use C. Otherwise, take advantage of the language you're using.

Max Lybbert
I'd use `std::ofstream` fro writing.
sbi
Thanks. Edited. I used fstream out of habit.
Max Lybbert