include include include S I dont remember what to include fo
#include <iostream>
#include <fstream>
#include <string>
//S: I don\'t remember what to include for a string stream, but I keep getting
//S: an error!
using namespace std;
int main()
{
string input_file;
string line;
istringstream sin;
ifstream fin;
int i, j, k;
cout << \"Enter input filename: \";
cin >> input_file;
cout << endl;
fin.open(input_file);
if (fin.fail()) {
cout << \"Unable to open input file.\ \";
return -1;
}
while (getline(fin, line)) {
//S: For some reason, sin gives me the first line with no problems, afterward
//S: I don\'t get any more information!
sin.str(line);
//S: Fields A, B, C are all optional, so I only print out those fields that
//S: exist in the line, however when I do sin >> i >> j >> k, how do I differentiate those
//S: fields that got data and those that did not.
if (sin >> i >> j >> k) {
cout << \"Field A = \" << i;
if (sin >> j) {
cout << \", Field B = \" << j;
if (sin >> k) {
cout << \", Field C = \" << k;
}
}
cout << endl;
}
}
return 0;
}
This is a debug for my general computer science class and I needed help on it. Highlighted are the parts that are given to correct the mistakes.
Solution
Here is the code for you:
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
//S: I don\'t remember what to include for a string stream, but I keep getting
//S: an error!
using namespace std;
int main()
{
string input_file;
string line;
stringstream sin;
ifstream fin;
int i, j, k;
cout << \"Enter input filename: \";
cin >> input_file;
cout << endl;
fin.open(input_file);
if (fin.fail()) {
cout << \"Unable to open input file.\ \";
return -1;
}
while (getline(fin, line)) {
//S: For some reason, sin gives me the first line with no problems, afterward
//S: I don\'t get any more information!
sin.str(line);
//S: Fields A, B, C are all optional, so I only print out those fields that
//S: exist in the line, however when I do sin >> i >> j >> k, how do I differentiate those
//S: fields that got data and those that did not.
if (sin >> i) {
cout << \"Field A = \" << i;
if (sin >> j) {
cout << \", Field B = \" << j;
if (sin >> k) {
cout << \", Field C = \" << k;
}
}
}
cout << endl;
}
return 0;
}

