warning: unused variable ‘arrPixel’ [-Wunused-variable] - c++

Main.cpp
#include <iostream>
#include <fstream>
#include "steganography.h" // call steganography class
const int arrSize = 30000;//array for contains pixels
using namespace std;
int main()
{
char FileName[20] = "new.txt";
char NewFile[20] = "new.ppm";
char arrPixel[arrSize] = {};
int count = 0;
int option;
Steganography A;//create the reference of steganopragpy class
cout<<"Choose Enocde/Decode[1/2]"; // take option from user
cin>>option;
switch(option)
{
case 1:
cout << "Enter PPM File Name" << endl;
cin>>FileName;
cout << "Enter Output File Name"<< endl;
cin>>NewFile;
A.readImage(FileName, arrPixel);//call readImage method
cout << "Encoded Successfully completed:" << endl;
A.printImage( NewFile, arrPixel);//write ppm
break;
case 2:
cout << "Enter Input File Name" << endl;
cin>>FileName;
cout << "Enter Output PPM File Name"<< endl;
cin>>NewFile;
A.readCipherText( NewFile, arrPixel);//call read file method
cout << "Decoded Successfully completed:" << endl;
A.printCipherText(FileName, arrPixel);//write ppm
break;
default:
cout<<"wrong choice";
}
// cout << NewFile << endl;
for(int ct = 0; ct > arrSize; ct++)
{
cout << arrPixel[ct];
}
return 0;
}
steganography.cpp
#include <iostream>
#include <fstream>
#include <string>
#include "steganography.h" // call steganography class
const int arrSize = 30000;//array for contains pixels
using namespace std;
Steganography::Steganography()//call steganography constructor
{
char arrPixel[arrSize] = {};
}
void Steganography::readImage(char* FileName, char* arrPixel)//read image
{
ifstream infile (FileName);//open file
if(infile.is_open())
{
for(int count = 0; count < arrSize; count++)
{
infile >> noskipws >> arrPixel[count];
}
}
else
{
cout << "Error opening new file." << endl;
//abort();
}
infile.close();
}
void Steganography::readCipherText(char* FileName, char* arrPixel)//read text file contains ppm info
{
ifstream infile (FileName);
if(infile.is_open())
{
for(int count = 0; count < arrSize; count++)
{
infile >> noskipws >> arrPixel[count];
}
}
else
{
cout << "Error opening new file." << endl;
//abort();
}
infile.close();
}
void Steganography::printImage(char* NewFile, char* arrPixel)//write image
{
ofstream outfile (NewFile);
if(outfile.is_open())
{
int count = arrSize;
for(int i = 0; i < (count - 1); i++)
{
outfile << arrPixel[i];
}
}
else
{
cout << "Error opening new file." << endl;
// abort();
}
outfile.close();
}
void Steganography::printCipherText(char* NewFile, char* arrPixel)//write ppm file
{
ofstream outfile (NewFile);
if(outfile.is_open())
{
int count = arrSize;
for(int i = 0; i < (count - 1); i++)
{
outfile << arrPixel[i];
}
}
else
{
cout << "Error opening new file." << endl;
// abort();
}
outfile.close();
}
steganography.h
#ifndef STEGANOGRAPHY_H
#define STEGANOGRAPHY_H
#include <string>
#include <vector>
class Steganography {
private:
// Image header
std::string image_type;
int width, height;
int max_color_depth;
// Image data
std::vector<int> color_data;
// Hidden data
std::string ciphertext;
int getNthBit(char cipher_char, int n);
public:
Steganography(void); //Constructor
void readImage(char*,char*);
void printImage(char*,char*);
void readCipherText(char*,char*);
void printCipherText(char*,char*);
void cleanImage();
void encipher();
void decipher();
};
#endif
When I compile, i get this warning:
steganography.cpp: In constructor ‘Steganography::Steganography()’:
steganography.cpp:11:10: warning: unused variable ‘arrPixel’ [-Wunused-variable]
Can someone help me figuring out the problem. Also,I have to write this line const int arrSize = 30000; in both Main.cpp and steganography.cpp to avoid getting errors, is there a way to write it only on steganography.cpp without getting errors?

Here:
Steganography::Steganography()//call steganography constructor
{
char arrPixel[arrSize] = {};
}
You declare a local variable called arrPixel and you don't use it. You can remove that line.
Note that you have a warning, not an error.

Related

C++ reading file search for something in that file

So I have a .txt file looking like this:
1:Meat Dish:Steak:11.5
2:Fish Dish:Fish and chips:12
The first number is the itemNo, 'Meat Dish' is my category, 'Steak' is my description and finally '11.5' is my price.
So basically I want to search for the itemNo and I want it to display the price from that line. This is what I have until now:
#include <iostream>
#include <fstream>
#include <string>
#include <vector> // We will use this to store Players
using std::string;
using std::ofstream;
using std::ifstream;
using std::cout;
using std::cin;
struct MenuList // Define a "Player" data structure
{
string itemNo;
string category;
string descript;
double price;
};
std::istream& operator>>(std::istream& infile, MenuList& menu)
{
// In this function we will define how information is inputted into the player struct
// std::cin is derived from the istream class
getline(infile, menu.itemNo, ':');
getline(infile, menu.category, ':');
getline(infile, menu.descript, ':');
infile >> menu.price;
// When we have extracted all of our information, return the stream
return infile;
}
std::ostream& operator<<(std::ostream& os, MenuList& menu)
{
// Just like the istream, we define how a player struct is displayed when using std::cout
os << "" << menu.itemNo << " " << menu.category << " - " << menu.descript;
// When we have extracted all of our information, return the stream
return os;
}
void Load(std::vector<MenuList>& r, string filename)
{
std::ifstream ifs(filename.c_str()); // Open the file name
if(ifs)
{
while(ifs.good()) // While contents are left to be extracted
{
MenuList temp;
ifs >> temp; // Extract record into a temp object
r.push_back(temp); // Copy it to the record database
}
cout << "Read " << r.size() << " records.\n\n";
}
else
{
cout << "Could not open file.\n\n";
}
}
void Read(std::vector<MenuList>& r) // Read record contents
{
for(unsigned int i = 0; i < r.size(); i++)
cout << r[i] << "\n";
}
void Search(std::vector<MenuList>& r) // Search records for name
{
string n;
cout << "Search for: ";
cin >> n;
for(int i = 0; i < r.size(); i++)
{
if(r[i].itemNo.find(n) != string::npos)
cout << r[i];
}
}
int main()
{
std::vector<MenuList> records;
Load(records, "delete.txt");
Read(records);
Search(records);
return 0;
}
I don't really know how to make it so it shows just the price without showing the whole line.
I have written my own code that reads in your text file and stores the information in a struct. Once you have a vector of MenuList, it is dead simple to only print what you want.
include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct MenuList // Define a "Player" data structure
{
string itemNo;
string category;
string descript;
double price;
};
void addToList(vector<MenuList*>& vector_menu_list, string& itemNo, string& category, string& descript, string& price)
{
MenuList* p_menu_list = new MenuList;
p_menu_list->itemNo = itemNo;
p_menu_list->category = category;
p_menu_list->descript = descript;
p_menu_list->price = std::stod(price);
vector_menu_list.push_back(p_menu_list);
}
vector<MenuList*> readFile(string filename, bool& error_encountered)
{
vector<MenuList*> vector_menu_list;
ifstream file;
file.open(filename);
if (file.is_open())
{
string itemNo;
string category;
string descript;
string price;
short number_of_colons_encountered = 0;
char c;
while (file.get(c))
{
if ('\n' != c && EOF != c)
{
if (':' == c)
{
number_of_colons_encountered++;
continue;
}
switch (number_of_colons_encountered)
{
case 0:
itemNo += c;
break;
case 1:
category += c;
break;
case 2:
descript += c;
break;
case 3:
price += c;
break;
default:
error_encountered = true;
file.close();
return vector_menu_list;
}
}
else
{
addToList(vector_menu_list, itemNo, category, descript, price);
itemNo.clear();
category.clear();
descript.clear();
price.clear();
number_of_colons_encountered = 0;
}
}
addToList(vector_menu_list, itemNo, category, descript, price);
error_encountered = false;
}
else
{
error_encountered = true;
}
file.close();
return vector_menu_list;
}
int main()
{
bool error_encountered;
vector<MenuList*> p_menu_list = readFile("menu list.txt", error_encountered);
if (true == error_encountered)
{
return -1;
}
cout << "List menu items:" << endl;
for (unsigned long long i = 0; i < p_menu_list.size(); i++)
{
cout << p_menu_list.at(i)->itemNo << " ";
cout << p_menu_list.at(i)->category << " ";
cout << p_menu_list.at(i)->descript << " ";
cout << p_menu_list.at(i)->price << endl;
}
cout << "\n\nHere are only the prices: " << endl;
for (unsigned long long i = 0; i < p_menu_list.size(); i++)
{
cout << p_menu_list.at(i)->price << endl;
}
for (unsigned long long i = 0; i < p_menu_list.size(); i++)
{
delete p_menu_list.at(i);
}
return 0;
}

Read and Write an Array of Structs to binary file. C++

This is a header file part of a bigger project, but I am trying to save an array of structs to a binary file. When I do this (with my current code) it reads back very random information and not sure if I am close to getting it right on saving the information.
#include <fstream>
using namespace std;
class Reserv{
private:
struct ReservStruct{
int seatNum = 0;
int custID = 0;
int resvID = 0;
int resvIDcount;
};
int resvIDcount;
static int const numberOfSeats = 10;
ReservStruct Seat[numberOfSeats];
public:
/* Read and Write Files ***********************************/
void writeResvIDcount(){
ofstream IDfile("resvidcount.txt", ios::binary);
IDfile.write((char*)&resvIDcount,sizeof(resvIDcount));
IDfile.close();
}
void readResvIDcount(){
ifstream IDfile("resvidcount.txt", ios::binary);
IDfile.read((char*)&resvIDcount,sizeof(resvIDcount));
IDfile.close();
}
void writeReservations(){
ofstream resfile("reservations.txt", ios::binary);
for (int i=0; i<numberOfSeats; i++) {
resfile.write((char*)&Seat[i], sizeof(Seat));
}
}
void readReservations(){
ifstream resfile("reservations.txt", ios::binary);
for (int i=0; i<numberOfSeats; i++) {
resfile.read((char*)&Seat[i], sizeof(Seat));
}
}
/*********************************************************/
void ReserveSeat(int seatNumber, int customerID){
if (Seat[seatNumber].resvID == 0) {
Seat[seatNumber].seatNum = seatNumber;
Seat[seatNumber].custID = customerID;
Seat[seatNumber].resvID = resvIDcount;
cout << "Reservation ID: " << resvIDcount << endl;
resvIDcount = resvIDcount+1;
writeResvIDcount();
writeReservations();
}
if (Seat[seatNumber].resvID != 0) {
addToWaitingList(seatNumber, customerID);
}
}
void CancelReservation(int seatNumber){
Seat[seatNumber].seatNum = seatNumber;
Seat[seatNumber].custID = 0;
Seat[seatNumber].resvID = 0;
cout << "Reservation on seat number " << Seat[seatNumber].seatNum << " has been cancelled." << endl;
}
Reserv(){
readResvIDcount();
readReservations();
int reservchoice;
cout << "1: New Reservation\n2: Cancel Reservation\n";
cin >> reservchoice;
if (reservchoice ==1) {
int customerID;
int seatToReserve;
cout << "Enter Customer ID:";
cin >> customerID;
cout << "Seat Number:";
cin >> seatToReserve;
ReserveSeat(seatToReserve, customerID);
}
if (reservchoice==2) {
int seatNum;
cout << "Seat Number:";
cin >>seatNum;
CancelReservation(seatNum);
}
}
};

c++ get array string from text file

my text file was like
Jason Derulo
91 Western Road,xxxx,xxxx
1000
david beckham
91 Western Road,xxxx,xxxx
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 name[30];
char address[50];
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].name, 30);
openfile.getline(record[loop].address, 50);
openfile >> record[loop].balance;
}
openfile.close(); //close text file
for (int i = 0; i <= loop + 1; i++) {
cout << "Account " << endl;
cout << "Name : " << record[i].name << endl;
cout << "Address : " << record[i].address << endl;
cout << "Balance : " << record[i].balance << endl;
}
}
}
Use ifstream::getline() instead of ifstream::eof() in tandem with >>. The following is an illustrative example, (and for simplicity I didn't check to see if the stream opened correctly).
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define ARR_SIZE 31
typedef struct {
char name[30];
char address[50];
double balance;
} ACCOUNT;
int main() {
ACCOUNT temp, record[ARR_SIZE];
ifstream ifile("list.txt");
int i=0;
double d=0;
while(i < ARR_SIZE) {
ifile.getline(temp.name, 30, '\n');//use the size of the array
ifile.getline(temp.address, 50, '\n');//same here
//consume the newline still in the stream:
if((ifile >> d).get()) { temp.balance = d; }
record[i] = temp;
i++;
}
for (int i=0; i < ARR_SIZE; i++) {
cout << record[i].name << "\n"
<< record[i].address << "\n"
<< record[i].balance << "\n\n";
}
return 0;
}
Another recommendation would be to use vectors for record array, and strings instead of char arrays.
REFERENCES:
Why does std::getline() skip input after a formatted extraction?

how to use strstr()?

i want to take data from file and store it in string array and and perform a search function with only few information like type"j" and the program able to look for data name which contain "j".
but my program cannot work.....
i am wondering am i using the strstr() correctly or not?
my text file :
Jason Derulo
5000
Martin Delux
8752
Justin Haber
51855
Alex Zander
52163
and
coding:
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
//---------------------------------------------------------------------------------------------------------
typedef struct
{
char name[30],adv_srh_name[30];
double balance;
}ACCOUNT;
int main()
{
ACCOUNT record[31];
int choice,acc_amount=0;
ifstream openfile("list.txt"); //open text file
if (!openfile)
{
cout << "Error opening input file\n";
return 0;
}
else
{
ACCOUNT temp;
int i = 0;
double d = 0;
while (openfile)
{
openfile.getline(temp.name, 30, '\n');
//consume the newline still in the stream:
if ((openfile >> d).get()) { temp.balance = d; }
record[i] = temp;
i++;
}
openfile.close(); //close text file
acc_amount = i;
}
cout << "Please enter a client name:";
fflush(stdin);
cin.getline(adv_srh_name, 30);
for (int j = 0; adv_srh_name[j] != NULL; j++)
adv_srh_name[j] = toupper(adv_srh_name[j]);
cout << adv_srh_name;
for (int a = 0; a < acc_amount; a++)
{
if ((strstr(record[a].name, adv_srh_name)) != NULL)
{
cout << "Name :" << record[a].name << "\n";
cout << "Balance :" << record[a].balance << "\n\n";
}
}
return 0;
}

C++. After writing into a relative file, I cannot display the content

I can write into a relative file1, then when I try to read the content and display it on the screen (to check if data are actually into the file), I do not have the records which I believe are already present in the file. I am using Dev-C++. Any help will be appreciated. The code is below;
#include <iostream> // cin, cout
#include <iomanip>
#include <fstream>
#include <conio.h>
using namespace std;
#define SIZE 10
struct client // Client record
{
int account; // from 1 to SIZE
char name[20];
double balance;
};
void make_file(char filename[], int number_of_records)
{
cout << "\nMAKE_FILE: Creating a blank relative file " << filename
<< " containing " << number_of_records << " records.";
ofstream OS(filename, ios::out);
if(!OS) {cerr << "File open error." << endl; exit(1);}
client blank={0, "", 0.0}; // Create an empty client record
while(number_of_records--)
OS.write((char *)&blank, sizeof(blank));
cout << "\nFile created.";
OS.close();
}
int main(void)
{
client c;
void *ptr;
int n=0;
char *fname = "credit.txt";
make_file(fname, SIZE);
fstream iof("credit.txt",ios::in | ios::out);
if(!iof)
{
cerr<<"File open error! "<<endl;
exit(1);
}
cout<<"\n\nenter the 10 customers into the file: "<< fname<<endl<<endl;
while(0 < c.account) // && c.account <= maxrec)
{
iof.seekp((c.account-1) * sizeof(client)); // position the pointer
iof.write((char *)&c, sizeof(c));
cout << "Account[1.."<< SIZE
<< "], Name, Balance (0 0 0 to exit)= ";
cin >> c.account >> c.name >> c.balance;
}
cout << "\n\nSHOW_FILE: The contents of file " << fname;
iof.seekg (0, ios::beg);
while(iof.read((char *)&c, sizeof(c))) //where I think the problem is
{
cout <<'\n'<< setw(3)<< ++n << setw(6) << c.account <<setw(20)
<< c.name << setw(10) << c.balance ;
// << " | " << IS.eof() << " " << ptr;
}
iof.close();
cout << "\n\n";
system("pause");
return 0;
}
A relative file is a file in which each record is identified by its ordinal position in the file allowing for random as well as sequential access.
Relative Files
Relative file organization
http://cayfer.bilkent.edu.tr/~cayfer/ctp108/relative.htm
You need to use binary reading/writing.
fstream iof("credit.txt",ios::in | ios::out | ios::binary);
In your code, in first loop, c.account is not initialitzed. Perhaps you are overwriting file with uninitialized values:
while(0 < c.account) // <--- c.account is not initialized!!
{
iof.seekp((c.account-1) * sizeof(client)); // position the pointer
iof.write((char *)&c, sizeof(c)); // <-- overwriting data??
You're program intrigued me since I haven't done too much work with iostream. If you were ever working with data that had to be edited on a per record basis you'd use some type of database or specialized library that would encapsulate you from all this stuff, such as an xml library. Since your data is so small it's easier to just load all of it into your application using an array of your data structs. After, when you've got new user input, it's easiest clear the file, and the write the data fresh. Here is what I did.
#include <stdio.h>
#include <tchar.h>
#include <iostream> // cin, cout
#include <iomanip>
#include <fstream>
#include <conio.h>
using namespace std;
#define SIZE 10
#define BUFFER_SIZE 100
#define NAME_SIZE 20
struct client // Client record
{
int account; // from 1 to SIZE
char name[NAME_SIZE];
double balance;
};
/* Makes file if files does not exist.
* Returns true if file already exists
*/
bool make_file(char filename[], int number_of_records)
{
// Check if file exists
fstream file;
file.open(filename, ios_base::out | ios_base::in); // will not create file
if (file.is_open())
{
file.close();
return true;
}
else
{
file.clear();
file.open(filename, ios_base::out);
if(!file) {cerr << "File open error." << endl; exit(1);}
cout << "File created. \n";
file.close();
return false;
}
}
/* Create an application that reads x number of accounts from a text file
* into an array of client data structures.
*/
int _tmain(int argc, _TCHAR* argv[])
{
client clientArray[SIZE];
char cleanName[NAME_SIZE];
for(int i = 0; i < NAME_SIZE; i++)
cleanName[i] = NULL;
// Make file if doesn't not exist.
char *fname = "credit.txt";
bool fileExisted = false;
fileExisted = make_file(fname, SIZE);
// initialize client array
for(int j = 0; j < SIZE; j++)
{
clientArray[j].account = -1;
strcpy_s(clientArray[j].name, cleanName);
clientArray[j].balance = 0.0;
}
// Open file and populate the client array
fstream readFile("credit.txt", ios::in | ios::binary);
if(fileExisted)
{
if(!readFile)
{
cerr<<"File open error! "<<endl;
exit(1);
}
int index = 0;
bool firstRun = true;
client temp;
while(index < SIZE)
{
readFile >> temp.account;
readFile >> temp.name;
readFile >> temp.balance;
if(readFile.eof())
break;
if(firstRun)
{
cout << "Data read \n";
cout << "----------\n";
firstRun = false;
}
clientArray[index].account = temp.account;
strcpy_s(clientArray[index].name, temp.name);
clientArray[index].balance = temp.balance;
cout << setw(3) << index+1;
cout << setw(6) << clientArray[index].account;
cout << setw(20) << clientArray[index].name;
cout << setw(10) << clientArray[index].balance << "\n";
index++;
}
readFile.close();
readFile.clear();
}
// Get user input
{
client temp; // Create and initialize temp client
temp.account = 0;
temp.balance = 0;
strcpy_s(temp.name, cleanName);
int index = 0;
bool keepLooping = true;
while(keepLooping)
{
cout << "Account[1.."<< SIZE << "], Name, Balance (-1 to exit)= ";
cin >> temp.account;
// If user exited
if(temp.account == -1)
keepLooping = false;
else
{
cin >> temp.name; // If not keep reading data
cin >> temp.balance;
// Find either unused account or same account
bool found = false;
int firstEmpty = -1;
for(int i = 0; i<SIZE; i++)
{
if(temp.account == clientArray[i].account) // Same account found
{
strcpy_s(clientArray[i].name, temp.name);
clientArray[i].balance = temp.balance;
found = true;
break;
}
else if((clientArray[i].account == -1)&&(firstEmpty == -1)) // Empty account found
{
firstEmpty = i;
}
}
if((firstEmpty != -1)&&(!found)) // Copy input to empty account
{
clientArray[firstEmpty].account = temp.account;
strcpy_s(clientArray[firstEmpty].name, temp.name);
clientArray[firstEmpty].balance = temp.balance;
}
else if(found) //
{
cout << "Updating Client Data. \n";
}
else // No empty accounts break loop
{
cout << "Client array is full!\n";
keepLooping = false;
}
}
}
} // end of user input scope
// Clear file and write only valid data to new file
{
ofstream out;
out.open("credit.txt");
for(int i=0 ; i<SIZE ; i++)
{
if(clientArray[i].account != -1)
{
out << clientArray[i].account << "\t";
out << clientArray[i].name << "\t";
out << clientArray[i].balance << "\n";
}
}
out.close();
out.clear();
}
// Open file and read the data
{
ifstream readFile("credit.txt", ios::in | ios::binary);
// readFile("credit.txt", ios::in | ios::binary);
if(!readFile)
{
cerr<<"File open error! "<<endl;
exit(1);
}
if(!readFile.good())
{
cerr<<"File open error!2"<<endl;
exit(1);
}
int index = 0; // scope variables
client temp;
temp.account = 0;
temp.balance = 0;
strcpy_s(temp.name, cleanName);
cout << "\nAccounts" << "\n";
cout << "----------" << "\n";
bool readFileb = readFile.good();
while(index < SIZE)
{
readFile >> temp.account;
readFile >> temp.name;
readFile >> temp.balance;
if(readFile.eof())
break;
cout << setw(3) << index+1;
cout << setw(6) << temp.account;
cout << setw(20) << temp.name;
cout << setw(10) << temp.balance << "\n";
index++;
}
readFile.close();
readFile.clear();
}
system("pause");
}