Reading file into vector through function - c++

I am trying to read the txt file into the vector in function readIn. I cannot for the life of me get it to work. Either I get the following message "error: expected primary-expression before '&' token
readIn(ifstream& infile, vec);" or the function isn't called at all.
int main() {
const int MAXSIZE = 100;
vector<int> vec (MAXSIZE);
ifstream infile;
infile.open("in9.3.txt");
readIn(ifstream& infile, vec);
return(0);
}
void readIn(ifstream& infile, vector<int> &vec) {
int a, count;
count = 0;
while (!infile.eof()) {
infile >> a;
vec.at(count) = a;
count++;
}
infile.close();
vec.resize(count);
}

You must not specify the type of the parameter when passing to a function. What you have written is incorrect:
readIn(ifstream& infile, vec); // error
Note that you are trying to pass the variable infile which is defined in main. The compiler is complaining about the fact that you prefixed this with ifstream&. The correct call is:
readIn(infile, vec);
Also beware that since the function is defined after main, there must be a function declaration somewhere before main. It is not clear whether you did this or not, since you have not shown a complete program. In any case, you can either move the whole definition before main, or just add this line:
void readIn(ifstream&, vector<int>&);

Related

Failure to read input from a file

I am unable to read an input from a file. Every time my code reaches strncpy, my code breaks and I am unable to figure out why. The code seems to break at the set name function.
fstream& AmaProduct::load(std::fstream& file){
char s[7];
char* n;
n = new char[7];
double p;
bool t;
int q;
int nn;
file.open("amaPrd.txt");
if (file.is_open()){
file.ignore(2);
file.getline(s,',');
cout << s;
sku(s);
file.ignore();
file.getline(n,',');
name(n);
file.ignore();
file >> p;
price(p);
file.ignore();
file >> t;
taxed(t);
file.ignore();
file >> q;
file.ignore();
quantity(q);
file.getline(unit_, ',');
file.ignore();
file >> nn;
qtyNeeded(nn);
}
file.close();
return file;
}
This is set here:
void Product::sku(char* sku){
strncpy(sku_,sku,7);
sku_[7]=0;
}
void Product::price(double price){
price_=price;
}
void Product::name(char* name){
delete[] name_;
name_= new char[strlen(name)+1];
strcpy(name_,name);
}
void Product::taxed(bool tax){
taxed_=tax;
}
void Product::quantity(int q){
quantity_=q;
}
void Product::qtyNeeded(int n){
qtyNeeded_=n;
sku being declared
char sku_[8]
I have been working on this for hours but have yet to find a solution.
Sorry for my previous answer that clearly wasn't correct.
A segmentation fault means your program is trying to access a memory location that doesn't belong to it. In other words, you're writing or reading a pointer that hasn't been (properly) initialized or is out of scope (plus a couple of other options that are less likely here).
You wrote that it crashes at strncpy, and its only reference is in the sku function. You have no "set name" function, but you have a strcpy call in the "name" function. Notice the difference between strncpy and strcpy.
Your function Product::sku(..) copies to sku_ using strncpy, but it is unclear where you are declaring it and whether it is in scope or has been initialized when Product::sku(..) runs. The main function is in a AmaProduct namespace (or class), while the others are in Product. Is that on purpose? In which namespace is sku_ declared?
The Product::name(char* name) function calls strcpy, which assumes that name is a zero-terminated string. Are you sure that it is zero-terminated? If not, it will continue to write and throw a segfault. It is probably also wise to add a maximum number of characters for file.getline() to read. The max number should correspond to the size of the destination buffer.
Also, it is considered unwise to name a function the same as a variable. Having clear and meaningful names makes it easier to see and debug the logic of your code.
Finally, see http://www.cprogramming.com/debugging/segfaults.html for more help on debugging.

How do I read from an input file after passing the ifstream object to a function?

as the title suggests, I am having a problem with not being able to read from an input file after passing the ifstream object to a class function. Basically I'm trying to sort a list of numbers using a heap ADT implemented with an array.
int main() {
ifstream infile("input.txt");
HeapSort* heap = new HeapSort(20); // creates a heap (array) with size 20
heap->buildHeap(&infile);
return 0;
}
void HeapSort::buildHeap(ifstream* infile) {
int data;
while (infile >> data) {cout << data << endl;}
infile->close();
}
the error occurs in the conditional of the while loop inside buildHeap. The compiler can't recognize the operator ">>" between an 'int' and an 'ifstream' object. However, strangely enough, if I write that same while loop inside main(), it'll work just fine. Also of note is that if I remove the while loop, the compiler returns no errors. Meaning, simply the act of passing the ifstream object from main to buildHeap is OK.
Please avoid suggesting alternative ways of achieving this. I was asked to not use any special fstream functions like eof(). I can only use the ">>" operator to read from the desired file.
You're passing a pointer to a stream, so you need to dereference it:
while (*infile >> data)
If you want your code to look like what you say you did in main, then you pass a reference:
heap->buildHeap(infile);
//...
void HeapSort::buildHeap(ifstream& infile)
{
int data;
while (infile >> data) { ... }
infile.close();
}

How to declare vector of structure type?

I have a problem with the code below. Here, I want to write a program which will take input from a file and store it in a vector of structure, but when I declare a structure type vector it is showing an error.
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
struct input
{
char process[10];
int burst_time;
int arrival_time;
}input;
int main()
{
ifstream myfile;
vector<input> store;// problem with initializing vector
myfile.open("input.txt",ios::in);
if(myfile.is_open())
{
while(!myfile.eof())
{
myfile>>input.process;
myfile>>input.burst_time;
myfile>>input.arrival_time;
store.push_back(input);//showing problem in this line also
}
}
myfile.close();
return 0;
}
You have hidden the name input to be an instance of struct input. Un-hide it:
struct intput
{
// as before
};
This is the thing, very simple:
When you declare
struct input
{
char process[10];
int burst_time;
int arrival_time;
} input;
you are defining a struct type named input but also a variable named input, so in the main the compiler gets confused, it doesn't know if you refer to variable or type, so just rename the struct variable declaration and refer to it as its own name like in this:
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
struct input // Type defined as "input"
{
char process[10];
int burst_time;
int arrival_time;
} input1; // And variable defined as "input1" consider this to be declared in main, to be a local variable.
int main()
{
ifstream myfile;
vector<input> store{};// problem solved referring to type and not variable
myfile.open("input.txt",ios::in);
if(myfile.is_open())
{
while(!myfile.eof())
{
myfile>>input1.process; // Here now the compiler understands that you are referring to the variable and not the type
myfile>>input1.burst_time;
myfile>>input1.arrival_time;
store.push_back(input1);
}
}
myfile.close();
return 0;
}
This way the compiler will not complain.
Consider also always you declare a new type (like your structure) with first character as upper case. Input instead, and variables with first character lower case input to not get confused and avoid this kind of mistakes.

No matching function - ifstream open()

This is the part of the code with an error:
std::vector<int> loadNumbersFromFile(std::string name)
{
std::vector<int> numbers;
std::ifstream file;
file.open(name); // the error is here
if(!file) {
std::cout << "\nError\n\n";
exit(EXIT_FAILURE);
}
int current;
while(file >> current) {
numbers.push_back(current);
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
return numbers;
}
And well, I kind of have no idea what is going on. The whole thing compiles properly in VS. However I need to compile this with dev cpp.
I commented out the line throwing errors in the code above. The errors are:
no matching function for call 'std::basic_ifstream<char>::open(std::string&)
no matching function for call 'std::basic_ofstream<char>::open(std::string&)
In different parts of code I get errors like numeric_limits is not a member of std, or max() has not been declared, although they exist in iostream class and everything works in VS.
Why am I getting this error?
Change to:
file.open(name.c_str());
or just use the constructor as there is no reason to separate construction and open:
std::ifstream file(name.c_str());
Support for std::string argument was added in c++11.
As loadNumbersFromFile() does not modify its argument pass by std::string const& to document that fact and avoid unnecessary copy.

arrays of structures and file I/O

//i have two errors in my code
#include <iostream>
#include<iomanip>
#include<fstream>
using namespace std;
struct PLAYER
{
string first_name;
string last_name;
};
void showFile(fstream&, PLAYER&); // line 13
int main()
{
const int MAX=21;
PLAYER array[MAX];
ifstream inputFile;
inputFile.open("PlayerNames.txt",ios::in);
if(inputFile)
{
showFile(inputFile, array); // line 22
}else
cout<<"\n\nError opening file";
inputFile.close();
return 0;
}
void showFile(fstream &file, PLAYER &array )
{
int index=0;
int p_num=1;
string lname, fname;
file>>lname>>fname;
while(!file.eof())
{
// array[index].last_name=
cout<<lname<<" "<<fname;
//array[index].first_name=fname;
//array[index].player_number=p_num;
index++;
p_num++;
file>>lname>>fname;
}
// cout<<"\n"<<index;
//cout<<lname<<" "<<fname;
}
This program worked finally untill i put it in functions.
I have two errors in this program
line 22 error: invalid intialization of reference type std:: fstream
line 13 error: in passing argument 1 of void showFile(std:: fstream&, PLAYER&)
An ifstream can't be converted to an fstream, only an istream.
In the documentation you can see basic_ifstream is derived from basic_istream, not basic_fstream.
Make your function:
void showFile(istream&, PLAYER&);
This is actually better in many ways. For one it's correct (c: But also it means you can test it with any input stream rather than just a file stream. It is more loosely coupled and programs to the more abstract interface.
You function declaration at line 13 shows you are passing 1 PLAYER object, not an array. If you want to stay with arrays, search StackOverflow for "[C++] pass array function".
I highly recommend using std::vector as it has easier syntax when passing to functions.