My current assignment tasks me with using fstream, which I now finally understand to an extent, but now I have a problem which I haven't seen since I learned Python. How can I stop this program from segfaulting? breakfasts.txt lists the name of a food item on one line, then the cost of the food item on the next, and my program should be taking, line by line, a string equal to the line on the text file, though instead I get an error, segmentation fault. What piece of illegal memory am I accessing here?
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
usingnamespace std;
int main()
{
ifstream inFile;
cout << fixed << showpoint << setprecision(2);
inFile.open("breakfasts.txt");
if(!inFile)
{ cout << "Cannot open the input file. Program Terminates!" << endl; return 1; }
string foodName[8];
string foodCost[8];
//We need to record the value by using getline(inFile,foodName[i]);
//Now we need to skip the first line, and get getline(inFile,foodCost[i]);
//Repeat this, incrementing the number of lines skipped by 1 each time.
for(int i = 0; i < 16; i++)
{
if(16 % (i+1) != 0)
{
getline(inFile,foodName[i]);
}
elseif(16 % (i+1) == 0)
{
getline(inFile,foodCost[i]);
}
}
return 0;
}
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
usingnamespace std;
int main()
{
ifstream inFile;
cout << fixed << showpoint << setprecision(2);
inFile.open("breakfasts.txt");
if(!inFile)
{ cout << "Cannot open the input file. Program Terminates!" << endl; return 1; }
string line[16]; //we'll later turn these into foodName[8] and foodCost[8]
string foodName[8];
string foodCost[8];
//if statement evaluates odd/even, if odd j++, if even, k++
for(int i = 0, j = 0, k = 0; i < 16; i++)
{
getline(inFile,line[i]);
cout << "Line " << i << ": " << line[i] << endl;
}
//We need to record the value by using getline(inFile,foodName[i]);
//Now we need to skip the first line, and get getline(inFile,foodCost[i]);
//Repeat this, incrementing the number of lines skipped by 1 each time.
//Get value[0], get value2[0],
return 0;
}