input from a file

In writing a function I will use a lot, I am having trouble getting input from a file:

1
2
3
4
5
6
7
8
9
10
11
12
13
string askfile(string question)
{
       string a;
       string line;
       ifstream thefile ( ask(question) );
       while(thefile.good()) {
         getline (thefile,line);
         a.append (line);
         a.append ("n");
       }
       thefile.close();
       return a;
}
First glance, problem may be the lack of initialization of your strings..
string a = "";

Well one way you can accomplish exactly your desired result, which may be slightly less ambiguous (at least to me):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string get_string_from_file(string file){
   string returnString = "";
   fstream file;

   file.open(file.c_str(),ios::in|ios::binary);

   char buf = file.get();
   while(!file.eof()){
     returnString += buf;
     buf = file.get();
   }

   file.close();

   return returnString;
}
First glance, problem may be the lack of initialization of your strings..


Object types are initialized upon their declaration. string a; calls the default constructor for string on a.



Well one way you can accomplish exactly your desired result, which may be slightly less ambiguous (at least to me):
1
2
3
4
5
char buf = file.get();
   while(!file.eof()){
     returnString += buf;
     buf = file.get();
   }


Do you have any specific reason to work with chars instead of with strings? There is no real reason to do this, you make the code less readible instead of more here.

Anyways, @OP: It would help if you would specify what exactly your problem is.
Last edited on
Topic archived. No new replies allowed.