C++ StringStream read and parse text file
#include <cstdio> #include <cstdlib> #include <fstream> #include <sstream> #include <iostream> using namespace std; bool parseString(const char* pString,char* pName, int arraySize,long& accountNum, double& balance){ istringstream inp(pString);/*w ww. j a va2s . c o m*/ inp.getline(pName, arraySize, ','); inp >> accountNum; inp >> balance; return !inp.fail(); } int main(int nNumberofArgs, char* pszArgs[]) { char szFileName[128] = "main.cpp"; ifstream* pFileStream = new ifstream(szFileName); if (!pFileStream->good()){ cerr << "Can't open " << pszArgs[1] << endl; return 0; } for(int nLineNum = 1;;nLineNum++){ char buffer[256]; pFileStream->getline(buffer, 256); if (pFileStream->fail()) { break; } cout << nLineNum << ":" << buffer << endl; char name[80]; long accountNum; double balance; bool result = parseString(buffer, name, 80, accountNum, balance); if (result == false){ cerr << "Error parsing string\n" << endl; continue; } cout << "Read the following fields:" << endl; cout << " name = " << name << "\n" << " account = " << accountNum << "\n" << " balance = " << balance << endl; ostringstream out; out << name << ", " << balance << " " << accountNum << ends; string oString = out.str(); cout << "Reordered fields: " << oString << endl; } return 0; }