0

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

2

1 Answer 1

6

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().

Sign up to request clarification or add additional context in comments.

3 Comments

@mhjd, good answer but maybe you could also say something about why the OP code while(readFile.good()) is wrong
@hmjd , now i get it line by line, but if i want to break it by delimiter , with the value is stored in string, how do i proceed
@user1777711 I think the best way is to get it line by line. Once you have one line you have to write string parsing code to break it up how you want to break it up. There's no quick way to do this, you just have to write the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.