开发者

std has no member 'getline'?

开发者 https://www.devze.com 2023-02-28 09:09 出处:网络
I\'m trying to use std::getline, but my compiler is telling me that getline isn\'t identified? #include <iostream>

I'm trying to use std::getline, but my compiler is telling me that getline isn't identified?

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <fstream>
#include <cstdlib>

int main(){
    using namespace std;
    string line;
    ifstream ifile("test.in");
    if(ifile.is_ope开发者_如何学Cn()){
        while(ifile.good()){
            getline(ifile,line);
        }
    }
}


std::getline is defined in the string header.

#include <string>

Also, your code isn't using anything from cstring, cstdio, cmath, or cstdlib; why bother including these?

EDIT: To clarify the confusion regarding the cstring and string headers, cstring pulls the contents of the C runtime library's string.h into the std namespace; string is part of the C++ standard library and contains getline, std::basic_string<> (and its specializations std::string and std::wstring), etc. -- two very different headers.


As ildjarn points out, the function is declared in <string>, and I'm suprised you didn't get an error at:

string line;

Also, this:

 while(ifile.good()){
      getline(ifile,line);
 }

is not the way to write a read loop. You MUST test the success of the read operation, not the current stream state. You want:

while( getline(ifile,line) ) {
}


this is happening because getline comes from the string library, you need to #include <string> or #include <cstring>

0

精彩评论

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