news.hku.hk wrote in news:40******@newsgate.hku.hk in comp.lang.c++:
Excuse me, could you point out why the command below will generate
error? And how to overcome this problem by still using string?? i know
char array is ok but i don't want to use it. Thanks a lot
int main(){
ifstream ifs("abc.txt", ios::in);
if (!ifs){
cerr << "Cannot open abc.txt for input" << endl;
return 1;
return 1 *isn't* portable, se code below for the only 2 portable
return values for main.
}
string buffer;
ifs.getline(buffer, 500, '\n'); // why has error this line
You need to use non-member std::getline with std::string:
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib> // EXIT_*
int main()
{
using namespace std;
istringstream ifs( "file content\nfor a\nusnet posting\n" );
if (!ifs)
{
cerr << "Cannot open abc.txt for input" << endl;
return EXIT_FAILURE;
}
string buffer;
int line = 0;
while ( getline(ifs, buffer) )
{
cout << "line " << ++line << ": " << buffer << '\n';
}
cout.flush();
/* return 0 and no return are equivalent to this
*/
return EXIT_SUCCESS;
}
HTH.
Rob.
--
http://www.victim-prime.dsl.pipex.com/