Re: basics

From: Gwar (xeno_at_xor.qua)
Date: 07/03/04


Date: Sat, 3 Jul 2004 13:36:13 -0700


On Sun, 4 Jul 2004, Edo wrote:

> this code below, a question about the results, it puts out
> file created
> world!
> But I expected it to only print out
> File created
> W

> #include <iostream>
> #include <fstream>
> #include <ios>
>
> using namespace std;
>
> int main()
>
> {
>
>
> ofstream File("text.txt");
> if (File){
> cout <<"file created"<<endl;
> }else{
> cout <<"file not created"<<endl;
> }
>
> File << "world!, Hello";
> File.close();
>
> ifstream iFile("text.txt");
> static char str[1]; //static, the array is
> //initialized, every cell NULLed
> iFile.seekg(ios::beg); //get back to the beginning of the file
> iFile >> str;
> cout << str << endl;
> iFile.close();
>
> system("pause");
> return 0;
> }
>

// Why mess around with the file when you can just mess with the string?
// If you wanted to get a single character, you could have just used a
// char & get
// char c;
// iFile.get(c);
// cout << iFile.put(c);

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

using namespace std;

int main()
{
 ofstream ofs("t.txt");
 if(!ofs)
   cout << "File not created" << endl;

  ofs << "Hello Earth" << endl;
  ofs << "Hello Mars!" << endl;
  ifstream ifs("t.txt");
  if(!ifs)
    cout << "File not opened" << endl;
  string s;
  while(getline(ifs, s, '\n'))
    cout << s.substr(6,5) << endl;
}



Relevant Pages