1

i have the next code:

  std::string line;
  std::ifstream myfile ("text.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      std::cout << line << std::endl;
    }
    myfile.close();
  }

is there a way to do it, and use char* instead of string?

Mat
  • 202,337
  • 40
  • 393
  • 406
user1106106
  • 277
  • 2
  • 7
  • 13

2 Answers2

5

Yes, if you really insist. There's a version of getline that's a member of std::istream that will do it:

char buffer[1024];

std::ifstream myfile("text.txt");

while (myfile.getline(buffer, sizeof(buffer))
    std::cout << buffer << "\n";
myfile.close();

Note, however, that most C++ programmers would consider this obsolescent at best. Oh, and for the record, the loop in your question isn't really correct either. Using string, you'd typically want something like:

std::string line;
std::ifstream myfile("text.txt");

while (std::getline(myfile, line))
    std::cout << line << "\n";
myfile.close();

or, you could use the line proxy from one of my previous answers, in which case it becomes simpler still:

std::copy(std::istream_iterator<line>(myfile),
          std::istream_iterator<line>(),
          std::ostream_iterator<std::string>(std::cout, "\n"));
Community
  • 1
  • 1
Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
3

So you're looking for a more "C-like" solution?

#include<cstdio>
#define ENOUGH 1000

int main() {

    char buffer[ENOUGH];

    FILE* f = fopen("text.txt", "r");
    while (true) {
       if (fgets(buffer, ENOUGH, f) == NULL) break;
       puts(buffer);
    }
    fclose(f);

    return 0;
}

...plus some check whether the file was correctly opened. In this case, you use fgets() on the file f, reading into the char* buffer. However, buffer has only ENOUGH space allocated and this limit is also an important parameter to the fgets() function. It will stop reading the line when reaching ENOUGH - 1 characters, so you should make sure the ENOUGH constant is large enough.

But if you didn't mean to solve this in a "C-like" way, but are still going to use <iostream>, then you probably just want to know that the c_str() method of std::string returns the char* representation of that std::string.

Imp
  • 8,409
  • 1
  • 25
  • 36