0

I need to know the syntax of how i can read a string from a file without using char array or char variable.
i want to declare a variable of string type but its giving error .
I have include <cstring>,<ctype> libraries.

int main()
{
  string s1;
  ifstream fin
  fin.open("myfile.txt");
  while( !fin.eof())
  {
    fin>>s1;   // this line is giving error
  }

  fin.close();

  return 0;
}

Edited by mike_2000_17: Fixed formatting

3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by mraza1_ch
0

You have many errors. Firstly, click the code tags button instead of typing them in (you need a back slash on the close code) You are missing a semi-colon [;] on line 4. Next, you have not included fstream. Also, you need to change the line you say "is giving error". You cannot simply write backwards and forwards. Check out this link:
http://www.cplusplus.com/doc/tutorial/files/
Also, you need to add

using namespace std;

under your includes, as you need to tell the compiler that you are using the standard reference for string.

Edited by SgtMe: n/a

-1
#include <iostream>
#include<string>
#include<fstream>
using namespace std;
void main()
{
    string a;
    ofstream file("test.txt");              // for writing a string in file
    {
        getline(cin,a);
        file<<a;
    }
    file.close();
    ifstream f("test.txt");
    {
        f>>a;
        getline(f, a);                   // for reading a string from file
        cout<<a;
    }
}

Edited by mike_2000_17: Fixed formatting

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.