简体   繁体   English

C ++ getline()函数

[英]c++ getline() function

I dont' quite understand how this function works. 我不太了解此功能的工作原理。

I wrote a simple programming reading one line with getline(). 我写了一个简单的程序,用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++. 我是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 . 您没有显示带有错误的代码,但是错误表明您尝试使用std::string类型的参数调用atoi atoi takes a C string ( man atoi ), so you need to call it like: atoi需要一个C字符串( man atoi ),因此您需要像这样来调用它:

atoi( line.c_str() );

Which function are you trying to call? 您尝试调用哪个功能? The gnu 'C' getline function or istream::getline? gnu'C'getline函数或istream :: getline吗?

istream::getline has the following signature istream :: getline具有以下签名

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: string line更改为char line[2000]如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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