Line 15: Reading from cin, read from "file".
Line 18: This would always set charsPerLine to 0. (12/100) would evaluate to 0. Make it (12.0/100.0)
Line 23-24: Not clear what are you trying to do. Remember getline() remove teh '\n' char. So you won't find that in captionText. This would crash also. Assuming that charsPerLine is 5 AND there is no space in first 5 chars of captionText. This loop will keep doing --i and would make i negative, which will result in crash. (to protect against the crash you can add one more condition i >= 0 as the first condition in the while, but I'm not sure what are you doing so can't say if it's correct to do)
Line 25: This would replace ith char, not insert '\n' as (i+1)th char.
Assuming that your file contains one caption per line; and you want to read each caption from the file, chop off the unwanted chars; and store these captions in a single std::string variable separated by '\n' you can do it like this:
while( ! EOF )
{
read eachLine from file
if( eachLine.size() > allowed_caption_size )
output_string += chopOff( eachLine ) + '\n' ;
else
output_string += eachLine + '\n' ;
}
//PS: remove extra '\n' at the end if required
Finally: I would suggest that you use vector instead of a single string containing all captions separated by '\n'. This seems to be a perfect usecase for vector. If you use it your function signature would look like this:
void get_caption (fstream& file,
vector<string>& captionTextsVec,
unsigned captionWidth)
//PS: captionLines not needed as captionTextsVec.size() would give you that