The Way to Programming
The Way to Programming
Try this sample, please let me know if something is not clear
std::ifstream ifs ("test.txt", std::ifstream::in);//Read the file in input mode string eachline; while(getline(ifs,eachline)){//Read each line into a string if(!ifs.good())//if it (file state) is no more valid break and close the file break; stringstream txtStream(eachline);//Insert the string to string stream for further processing txtStream.ignore(eachline.length(),':');// Ignore the T1: part since we are not interested in it std::string token;//to contain each element that we are interested in while(std::getline(txtStream, token, ',')) {//Get elements seperated by comma into the token variable. std::cout << token << ',';// This token might still contain white spaces //You can read this token and insert into your vector } std::cout << endl;//Insert new line } ifs.close();//Close the file stream handle
keep the file handle open for as less time as possible in case if it is a shared resource. If it involves pretty straightforward and small amount of string processing it might still not create any problems. But if you plan to do more string processing and formatting after reading each line and if file can contain lot of records then it would be ideal that you read the entire file into a string. And the perform all the string processing and formatting in memory without keeping the file handle open for the entire time when string processing is done. It depends on how the file is updated by other clients
Sign in to your account