Lecture22
Lecture22
Computer Programming
Dr. Deepak B Phatak
(with Dr. Supratik Chakraborty)
Department of Computer Science and Engineering
IIT Bombay
Introduction
• setw(…)
• Header file: iomanip
• Same example where n is -77
10101,Anil Shah,112,12.5
10102,Amit Jadhav,111,15
10103,Shefali Pandya,112,17
10104,Rajesh Mashruwala,111,19
10105,Nandan Meshram,111,16
10106,Avinash Adsule,112,14
10107,Srikant Rao,112,14.5
10108,Nilmani Raut,111,11.5
10110,Rajesh Singh,112,10
10115,Ketan Maheshwari,111,12
Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, IIT Bombay 22
A program to process data from a CSV file
IIT Bombay
|1|0|1|0|1|,|A|n|I|l| |S|h|a|h|,|1|1|2|,|1|2|.|5|
sroll
sname
sbatch
smarks
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<iomanip>
using namespace std;
int main() {
string linestr, sroll, sname, sbatch, smarks;
int count = 0;
ifstream fin("CSV_data.txt", ios::in);
if(!fin.is_open()){
cout << "Could not open file" << endl;
return -1;
}
Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, IIT Bombay 27
Program …
IIT Bombay
while(getline(fin,linestr,'\n')){
stringstream X(linestr);
getline(X,sroll,','); getline(X,sname,',');
getline(X,sbatch,','); getline(X,smarks,',');
fout << sroll << " " << setw(30) << sname << " " << sbatch
<< " " << smarks << endl;
cout << sroll << " " << setw(30) << sname << " " << sbatch
<< " " << smarks << endl;
count++; //No. of records
} // End of while
Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, IIT Bombay 29
Program …
IIT Bombay
fin.close();
fout.close();
return 0;
}
Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, IIT Bombay 30
Execution results
IIT Bombay
int main() {
struct studentinfo s;
string linestr;
ifstream fin("CSV_data.txt", ios::in);
if(!fin.is_open()){
cout << "Could not open text file" << endl;
return -1;
}
while(getline(fin,linestr,'\n')){
/* extract differentt values in member variables of s
e.g. s.roll, etc */
fout.write((char*)&s, sizeof(s));
count++;
}
fin.close();
fout.close();
return 0;
}
Dr. Deepak B. Phatak & Dr. Supratik Chakraborty, IIT Bombay 45
Results of execution
IIT Bombay
fp POS
• Current position can be found using member function tellg
long POS; POS = fin.tellg();
• Reading/writing happens at this position
• You may set the position to a value POS by
fin.seekg(POS, ios::beg)