why can't use string for getline()?

N

news.hku.hk

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;
}

string buffer;
ifs.getline(buffer, 500, '\n'); // why has error this line

Billy
 
R

Rob Williscroft

news.hku.hk wrote in 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.
 
J

John Harrison

news.hku.hk said:
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

getline(ifs, buffer);

john
 
R

Rob Williscroft

Jacek Dziedzic wrote in in
comp.lang.c++:
Rob said:
[...]
return 1 *isn't* portable,
[...]

In what sense?

curious,
- J.

In the context of Standard C++.

The Standard gives us 2 portable values to return from main()
EXIT_SUCCESS and EXIT_FAILURE, they're defined in <cstddef> and
they are macros. Additionaly we can return 0 from main() and
that is required to be the same as returning EXIT_SUCCESS.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,117
Latest member
Matilda564
Top