开发者

C++: Read from files? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Reading through file using ifstream

I'm trying to find a way to read something from a file, put it into a st开发者_运维百科ring and then output it onto the screen. If you know how to do this can you give an example?


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

// Reads the first line from the file and stores it into 'line'
std::getline(infile, line);

infile.close();
std::cout << line;

This code will read the entire first line of the file. If you want to read the file line by line you could do something like this:

while (!infile.eof) {
  std::getline(infile, line);
  std::cout << line << "\n"; // Not sure if std::getline includes the line terminator
}

Not sure what you mean by 'need to read something', but you could use a stringstream for conversions.


ifstream fin ("input.txt");

char line [200];
streamsize size (200);
fin.getline(line, size);
//or you could do:
//  string str; fin >> str;
//for every space sepped string in the file
cout << line << endl;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜