I have a problem with a function that is having ifstream and string in it.
This my code:
#include <iostream>
#include <time.h>
#include <iomanip>
#include <stdlib.h>
#include <fstream>
#include <string>
const int ArrayMax = 100;
int DisplayMenu();
void LoadNames();
void ReadFile(ifstream& , ifstream& ,string[],string[]);
using namespace std;
int main()
{
ifstream FemaleFile;
ifstream MaleFile;
string Female[ArrayMax];
string Male[ArrayMax];
DisplayMenu();
ReadFile(FemaleFile, MaleFile, Female,Male );
return 0;
}
int DisplayMenu() //Displays menu and returns user selection
{
//variables
int selection;
//Headers
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl;
cout << " Name Guess Game" << endl;
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << endl;
cout << " Selaect Name Category" << endl;
cout << " 1. Female Names" << endl;
cout << " 2. Male Names" << endl;
cout << " 3. Exit" << endl << endl;
cout << " Enter 1, 2 or 3: " ;
cin >> selection;
while ((selection != 1) && (selection != 2) && (selection != 3) )
{
cout << " Invaild choice, Please Enter 1, 2 or 3: " ;
cin >> selection;
}
return selection;
}
void LoadNames()//Loads name lists from data files into two arrays and returns array sizes. Uses ReadFile(…) function
{
return;
}
void ReadFile(ifstream & FemaleFile ,ifstream & MaleFile, string Female[], string Male[] )//Reads the data of the received file into the received array size and returns the array size.
{
//opening files
FemaleFile.open("female.txt");
MaleFile.open("male.txt");
//Testing files
if (!FemaleFile){
cout << "Error, cannot open this file\n";
return;}
if (!MaleFile){
cout << "Error, cannot open this file\n";
return;}
for (int i=0 ; i < ArrayMax; i++)
{
FemaleFile >> Female[i];
cout << Female[i] << endl;
}
for (int i=0 ; i < ArrayMax; i++)
{
MaleFile >> Female[i];
cout << Male[i] << endl;
}
//closeing files
FemaleFile.close();
MaleFile.close();
return;
}
It is always give me this ERROR:
error C2065: 'ifstream' : undeclared identifier
error C2059: syntax error : ','
error C3861: 'ReadFile': identifier not found
Can you help me with this, please?
I think you put using namespace std; before your functions declaration. I mean add this before int DisplayMenu();. Then it would be OK.
You lost std::ifstream before
using namespace std;
in the function declaration.
Related
I'm working on a program that I've seen other people do online except I'm trying to use functions to complete it to make it somewhat more challenging for me to help me better understand pointers and vectors. The problem I'm having in xcode is I keep getting this error..
Expected ';' after top level declarator
right here on my code,
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers) //<<< Error
{
cout << fixed << setprecision(2);
...
Where I am trying to use vector numbers in my function. Basically I want the numbers from the function passed back so that I can use them in another function I have not created yet. I've googled this error and it seems like no one can give a straight answer on how to fix this problem. Is anyone familiar with how to correct this? By no means is this code finished I'm just trying to get information regarding vectors as a parameter because from what I'm seeing syntax wise on other sites it looks to be correct. Thanks for your feedback.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
struct menuItemType{
string menuItem;
double menuPrice;
};
void getData(menuItemType (&mlist)[8]);
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
int main() {
vector<int> temp;
menuItemType menuList[8];
getData(menuList);
showMenu(menuList,temp);
/*
cout << menuList[0].menuItem << " " << menuList[0].menuPrice << endl;
cout << menuList[1].menuItem << " " << menuList[1].menuPrice << endl;
*/
return 0;
}
void getData(menuItemType (&mlist)[8]){
string Str;
ifstream infile;
infile.open("cafe135.txt");
if(infile.is_open())
{
for (int i = 0; i < 8; ++i){
infile >> mlist[i].menuItem >> mlist[i].menuPrice;
}
}
else cout << "Unable to open file";
}
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
{
cout << fixed << setprecision(2);
string choice;
cout << "Would you like to view the menu? [Y] or [N]: ";
cin >> choice;
cout << endl;
int x = 3;
int count = 1;
while (choice != "Y" && choice != "N" && choice != "y" && choice != "n")
{
if (count == 4){
return;
}
cout << "Error! Please try again ["
<< x
<< "] selections remaining: ";
cin >> choice;
cout << endl;
x--;
count++;
}
if (choice == "N" || choice == "n"){
return;
}
else
{
cout << "___________ Breakfast Menu ___________" << endl;
for (int i = 0; i < sizeof(menu_List)/sizeof(menu_List[0]); ++i)
{
cout << "Item "
<< (i+1)
<< ": "
<< menu_List[i].menuItem
<< " "
<< menu_List[i].menuPrice
<< endl;
}
cout << endl;
string itemSelection = " ";
//int str_length = 0;
cout << "Select your item numbers separated"
<< " by spaces (e.g. 1 3 5) Select 0 to cancel order: ";
cin.ignore();
getline(cin, itemSelection);
if (itemSelection == "0")
{
return;
}
vector<int> vectorItemSelection;
stringstream text_stream(itemSelection);
string item;
while (getline(text_stream, item, ' '))
{
vectorItemSelection.push_back(stoi(item));
}
int n = vectorItemSelection.size();
int arr[n];
for (int i = 0; i < n; i++)
{
arr[i] = vectorItemSelection[i];
}
}
}
Compare how menu_List is declared in this line
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
and this line
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
The first one is correct.
But I have to agree with the comments above, you are mixing up a lot of different things here. Just use vectors, 99% of the time it's the right thing to do anyway. and it's easier to learn one thing at a time.
Prefer to write your code like this
void getData(vector<menuItemType>&);
void showMenu(vector<menuItemType>&, vector<int> numbers);
int main() {
vector<int> temp;
vector<menuItemType> menuList(8);
...
See? Just use vectors everywhere.
So in this assignment I have to have one function that has the user enter the vector which is the driver name and then they enter the drivers 4 points. That function is fine. I also Have to do a second function that writes the name and the average that I get from the 4 points to the txt file. and then display the name and averages in main. Right now I am stuck on the second function because I'm having trouble getting it to where it would write the vector and then the average after it. right now it is writing both vector elements and then the first average, and then both vector elements and the second average. can someone help me
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
#include <fstream>
using namespace std;
//function prototypes
void Enter_Driver_Data(vector<string> &driverName, int points[8][4], string fileName, fstream& file, int& counter);
void Calculate_Average(vector<string> &driverName, int points[8][4], string fileName, fstream& file, int& counter);
int main()
{
int counter = 0;//this counter is for the average function
int points[8][4];
vector<string>driverName;
fstream file;
string fileName;
int average;
//user will enter a text file name
cout << "Please enter the file name: ";
getline(cin, fileName);
Enter_Driver_Data(driverName, points, fileName, file, counter);
Calculate_Average(driverName, points, fileName, file, counter);
cout << setprecision(1) << fixed << endl;
fstream txtInput(fileName, ios::in);
//outputting the txt file data
for (string i : driverName)
{
cout << i << "'s average points is: ";
txtInput >> average;
cout << endl;
}
cout << endl << endl;
system("pause");
return 0;
}
void Enter_Driver_Data(vector<string> &driverName, int points[8][4], string fileName, fstream& file, int& counter)//this function is for entering data
{
file.open(fileName, ios::out);
string driverNameInput;
//filestream declarations
fstream txtOutput(fileName, ios::out);
//again declaration
bool again = true;
//for loop for data
for (int name = 0; name < 8 && again; name++)//name is for the row of the array
{
cout << "\nPlease enter the driver's name: ";
getline(cin, driverNameInput);
driverName.push_back(driverNameInput);
txtOutput << driverName[name] << ": ";
for (int score = 0; score < 4; score++)//score is for the column of the array
{
cout << "\nPlease enter " << driverName[name] << "'s score number " << score + 1 << ": ";
cin >> points[name][score];
while (points[name][score] != 60 && points[name][score] != 70 && points[name][score] != 80 && points[name][score] != 90 && points[name][score] != 100)
{
cout << "Your input was invalid: please enter the scores which are 60, 70, 80, 90,or 100: ";
cin >> points[name][score];
}
cout << points[name][score] << endl;
txtOutput << points[name][score] << " ";
cin.ignore();
cin.clear();
}
txtOutput << endl;
cout << "Would you like to enter another driver?(1 for yes and 0 for no): ";
cin >> again;
cin.ignore();
cin.clear();
counter++;
}
file.close();
}
void Calculate_Average(vector<string> &driverName, int points[8][4], string fileName, fstream& file, int& counter)
{
file.open(fileName, ios::app);
fstream txtOutput(fileName, ios::app);
double totalBeforeAverage, average;
vector <double> avg;
for (int name = 0; name < counter; name++)
{
totalBeforeAverage = 0, average = 0;
for (int score = 0; score < 4; score++)
{
totalBeforeAverage += points[name][score];
}
average = totalBeforeAverage / 4;
avg.push_back(average);
}
for (string drivName : driverName)
{
txtOutput << drivName << ": ";
}
for (double averageToFile : avg)
{
txtOutput << averageToFile << endl;
}
file.close();
}
I have a file I want to continue calling on in different functions in my program. It worked fine as a reference in the shiftText function but when I repeated the reference in the next function, all that returns is 0,
Can I get a small hint at something I am missing perhaps to make it behave this way? Thanks!
(PS there's definitely a lot of 'fat' in this that I have included for testing purposes only)
I will eventually return the value of "e" into the shiftText function if you were curious why that's there :)
#include <iostream>
#include <cmath>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
void inputfile(ifstream &masterfile) // ask for file name
{
string filename;
cout << "Please enter the name and extension of your file " << endl;
cin >> filename;
masterfile.open(filename);
if (!masterfile)
{
cout << "warning: cannot open file" << endl;
exit(1);
}
}
int findShift(ifstream &file, int counter[]) // find most used char
{
char ch;
int code;
while (file.get(ch))
{
code = static_cast<int>(ch);
cout << code << " ";
counter[code]++;
}
int max, min;
int indexMax, indexMin;
max = counter[65];
indexMax = 65;
min = counter[65];
indexMin = 65;
for (int i = 66; i <= 122; i++)
{
if (counter[i] > max)
{
max = counter[i];
indexMax = i;
}
if (counter[i] < min)
{
min = counter[i];
indexMin = i;
}
}
cout << endl
<< "Most frequent was " << indexMax;
return indexMax;
}
void shiftText(ifstream &file) // this is where my program skips over my ifstream reference
{
char ch;
int code;
while (file.get(ch))
{
code = static_cast<int>(ch);
cout << code << " ";
}
}
char stopFlashing() // for sanity
{
char reply;
cout << endl
<< "Press q (or any other key) followed by 'Enter' to quit: ";
cin >> reply;
return 0;
}
int main()
{
int counter[256] = {0};
ifstream file;
inputfile(file);
int e = findShift(file, counter);
shiftText(file);
cout << endl << " " << file << " " << endl; // for testing, a zero is returned
stopFlashing();
}
In function findShift you loop over the file. In function shiftText you are trying to do the same. However, the file is already at its end. Before calling shiftText you should rewind the file by using seekg:
file.seekg(0, std::ios_base::beg)
my text file was like
123456123456
Jason
uk
012456788
1000
456789456789
david
uk
012456788
1000
i'm trying to get the data from a text file and save it into arrays
however when i want to store the data from the text file into array it loop non-stop.
what should i do ?
the problem exiting in looping or the method i get the data from text file ?
code:
#include <iostream>
#include <fstream>
using namespace std;
typedef struct {
char acc_no[12];
char name[30];
char address[50];
char phone_no[12];
double balance;
} ACCOUNT;
//function prototype
void menu();
void read_data(ACCOUNT record[]);
int main() {
ACCOUNT record[31]; //Define array 'record' which have maximum size of 30
read_data(record);
}
//--------------------------------------------------------------------
void read_data(ACCOUNT record[]) {
ifstream openfile("list.txt"); //open text file
if (!openfile) {
cout << "Error opening input file\n";
return 0;
} else {
int loop = -1; //size of array
cout << "--------------Data From File--------------"<<endl;
while (!openfile.eof()) {
if (openfile.peek() == '\n')
openfile.ignore(256, '\n');
openfile.getline(record[++loop].acc_no, 12);
openfile.getline(record[loop].name, 30);
openfile.getline(record[loop].address, 50);
openfile.getline(record[loop].phone_no, 12);
openfile >> record[loop].balance;
}
openfile.close(); //close text file
for (int i = 0; i <= loop + 1; i++) {
cout << "Account " << endl;
cout << "Account No. : " << record[i].acc_no << endl;
cout << "Name : " << record[i].name << endl;
cout << "Address : " << record[i].address << endl;
cout << "Phone Number : " << record[i].phone_no << endl;
cout << "Balance : " << record[i].balance << endl;
}
}
}
UPDATE:
The OP didn't properly cite the correct format in his data file. This answer is only valid up until the last iteration.
Don't use .eof() - that's more applicable to when you want to open the file and read it by characters.
A better way would be to use the insertion operator >> as follows:
#define ARR_SIZE 31
ACCOUNT temp;
ACCOUNT record[ARR_SIZE];
int i=0;
while(i < ARR_SIZE) {
openfile >> temp.acc_no >> temp.name >> temp.address >> temp.phone_no >> temp.balance;
record[i] = temp;
i++;
}
Of course, even better is to use std::string to hold the values from the input file, in addition to using std::vectors instead of arrays.
The program works all the way up until it checks for the name the user enters. When you enter the name you wish to search for in the array of structures that have been imported from a file full of customer info) it comes back segmentation fault core dumped. This puzzles me.
#include <iostream>
#include <string>
#include <fstream>
#include <cstring>
using namespace std;
struct AccountsDataBase{
char name[50];
string email;
long int phone;
string address;
};
#define MAX 80
AccountsDataBase * account = new AccountsDataBase[MAX];
void readIn(ifstream& file){
int i=0;
while(!file.eof()){
file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}
}
void getAccount(){
char userPick[50];
char streamName[50];
cout << " What account will we be using? " << endl;
cin.getline(streamName, 50);
for(int i=0; strcmp(account[i].name, streamName)!=0; i++){
if( strcmp(account[i].name, streamName)==0){
cout << "\n\n FOUND IT!! \n\n";
cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
}
}
}
int main(){
ifstream file;
file.open("2.dat"); //opens data account records text
readIn(file);
getAccount();
delete account;
return 0;
}
Your loop keeps reading everything into the initial element of the array:
while(!file.eof()){
file >> account[i].name >> account[i].email >> account[i].phone >> account[i].address;
}
because the value of i is never incremented. You can convert this to a for loop, like this:
for (count = 0 ; count < MAX && !file.eof() ; count++) {
file >> account[count].name >> account[count].email >> account[count].phone >> account[count].address;
}
Note that I changed i to count:
AccountsDataBase * account = new AccountsDataBase[MAX];
int count = 0;
This will help you solve another problem - determining when the array ends in the getAccount function. Currently, you assume that the record is always there, so the outer loop keeps going on. Now that you have count, you could change the loop like this:
for(int i=0; i < count && strcmp(account[i].name, streamName)!=0; i++){
if( strcmp(account[i].name, streamName)==0){
cout << "\n\n FOUND IT!! \n\n";
cout << account[i].name << "\n" << account[i].email << "\n" << account[i].phone << "\n" << account[i].address << endl;
break;
}
}
if (i == count) {
cout << "Not found." << endl;
}