ifstream get line change output from char to string

C++ ifstream get line change getline output from char to string

I got a text file.. so i read it and i do something like

char data[50];
readFile.open(filename.c_str());

while(readFile.good())
{
readFile.getline(data,50,',');

cout << data << endl;

}

My question is instead of creating a char with size 50 by the variable name data, can i get the getline to a string instead something like

string myData;
readFile.getline(myData,',');

My text file is something like this

Line2D, [3,2] Line3D, [7,2,3]

I tried and the compiler say..

no matching function for getline(std::string&,char)

so is it possible to still break by delimiter, assign value to a string instead of a char.

Updates:

Using

while (std::getline(readFile, line))
{
    std::cout << line << std::endl;
}

IT read line by line, but i wanna break the string into several delimiter, originally if using char i will specify the delimiter as the 3rd element which is

readFile.getline(data,50,' , ');

how do i do with string if i break /explode with delimiter comma , the one above. in line by line


Use std::getline() :

std::string line;
while (std::getline(readFile, line, ','))
{
    std::cout << line << std::endl;
}

Always check the result of read operations immediately otherwise the code will attempt to process the result of a failed read, as is the case with the posted code.

Though it is possible to specify a different delimiter in getline() it could mistakenly process two invalid lines as a single valid line. Recommend retrieving each line in full and then split the line. A useful utility for splitting lines is boost::split() .

链接地址: http://www.djcxy.com/p/31534.html

上一篇: C:printf()和putchar()问题

下一篇: ifstream从char获取行更改输出到字符串