简体   繁体   中英

c++ getline() function

I dont' quite understand how this function works.

I wrote a simple programming reading one line with getline().

for example:

ifstream in;
in.open("example.txt");
string line;
getline(in, line);
cout << line << endl;

When I tried to run this program I received an error message like this.

`assign1_2.cpp:33:20: error: cannot convert 'std::string {aka std::basic_string<char>}'    to 'const char*' for argument '1' to 'int atoi(const char*)'

I simply don't understand what went wrong here. Please help!. I am a newbie to c++.

You didn't show the code with the error, but the error says you tried to call atoi with an argument of type std::string . atoi takes a C string ( man atoi ), so you need to call it like:

atoi( line.c_str() );

Which function are you trying to call? The gnu 'C' getline function or istream::getline?

istream::getline has the following signature

istream& istream::getline( char* str, streamsize count)
istream& istream::getline( char* str, streamsize count, char delim )

So you call should be something like:

char* buf[1000]
in.getline( buf, 1000 );

Change string line to char line[2000] like so:

#include <iostream>
#include <fstream>
using namespace std;


int main()
{
    char line[2000];
    fstream in;

    in.open("example.txt",ios::in);

    while(!in.eof()) 
    {
          in.getline(line,2000);
    }   

    in.close();
    cout <<line;
    cout <<endl;

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM