For the last day I have had some problems with this code. Here I want to upload with a .txt several hexadecimal values and if the sum of the first five numbers is equal to the last number, the code is correct.Then, the method main have to check if the rest methods were succeeded. But I don't know how do this, so I need your help...
#include <iostream>
#include <fstream>
#define FILECODE "file.txt"
#define N_CODE 6
using namespace std;
ifstream file;
void uploadCode(bool& exist, unsigned int longCode, unsigned int code[]);
bool IsValidCode(unsigned int code[]);
void main() {
unsigned int code[N_CODE];
bool exist;
unsigned int longCode=N_CODE;
IsValidCode(code);
if(IsValidCode(code)==true){
uploadCode(exist,longCode,code); //here I have the problem because I don't know how to call the method
cout << "SUCCESS" << endl;
}
else
cout << "FAIL" << endl;
}
void uploadCode(bool& exist, unsigned int longCode, unsigned int code[]) {
int i;
file.open(FILECODE);
if(file){
exist=true;
for(int i=0;i<longCode;i++){
file >> hex >> code[i];
cout << "Number " << i << ": "<< code[i] << endl;
}
cout << "EXIST" << endl;
}
else
cout << "NO EXIST" << endl;
exist=false;
file.close();
}
bool IsValidCode(unsigned int code[]) {
int i;
int sum=0;
for(int i=0; i<N_CODE-1; i++)
sum+=code[i];
cout << "Sum first five numbers: " << sum << endl;
if(sum==code[6])
return true;
else
return false;
return sum;
}
Here's a minimally modified version that does what you want. Of course, much better checks should be done on the return values of your input processing (i.e. - file >> hex >> code[i];) to see if those inputs are actually succeeding or not.
bool uploadCode(unsigned int longCode, unsigned int code[])
{
bool ret;
file.open(FILECODE); // TODO: no need for a global here; just use a locally constructed ifstream
if (file.good())
{
ret = true;
for(int i = 0; i < longCode; ++i)
{
file >> hex >> code[i];
cout << "Number " << i << ": "<< code[i] << endl;
}
cout << "EXIST" << endl;
}
else
{
ret = false;
cout << "NO EXIST" << endl;
}
file.close();
return ret;
}
int main()
{
unsigned int code[N_CODE];
if (!uploadCode(N_CODE, code))
{
cout << "File failure!" << endl;
return 1;
}
if (!IsValidCode(code))
{
cout << "Code failure!" << endl;
return 2;
}
cout << "SUCCESS" << endl;
return 0;
}
In your main function, you are calling IsValidCode twice before the data is read from the file. I don't think this is what you want.
A preferred method is:
Read first 6 numbers.
Sum the first 5 numbers.
If the sum != 6th number, return error status from main().
You don't need to make separate functions for each item above. Put them all in the main function. (The overhead to call and return from the simple functions may be more code than contained in the function.)
Edit 1: An example
int main(void)
{
const unsigned int CODE_LENGTH = 6;
ifstream input_file("file.txt");
if (!input_file)
{
cerr << "Error opening file.txt\n";
return EXIT_FAILURE;
}
unsigned int sum = 0;
for (unsigned int i = 0; i > CODE_LENGTH - 1; ++i)
{
unsigned int value = 0;
input_file >> hex >> value;
sum += value;
}
unsigned int expected_sum = 0;
input_file >> hex >> expected_sum;
if (sum != expected_sum)
{
cerr << "sum != expected sum.\n";
return EXIT_FAILURE;
}
// ....
return EXIT_SUCCESS;
}
Simple, no arrays necessary, no additional functions.
Related
I want this c++ program to find the the words starting with user entereed letter and print them using a new function.but the thins is that it only finds 1st letter for the second time it runs ina loop and then , i dont know what happens ... I am a beginner please help me!
uncomment the line that are necessary
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
void getUserInput(string *filename, string *find)
{
cout << "file name : ";
cin >> *filename;
cout << "required character : ";
cin >> *find;
}
string* processFile(string fileName, string word, int *t, int *w, string found[])
{
fstream file;
int countIn = 0,
totaal = 0;
int *count = &countIn;
int *total = &totaal;
int i = 0;
string find; // the max length of the file should not exceed this value is if does please change it here.
file.open(fileName, ios::in);
if (file.is_open())
{
while (!file.eof())
{
file >> find;
totaal++;
if (word == find)
{
char a[100];
int s = find.size();
for (int j = 0; i < find.size(); j++)
{
string(1, find[i]);
}
found[i] = find;
i++;
countIn++;
}
}
}
else
cout << "!!!!invalid file name!!!!\n";
file.close();
//for (int i = 0, j = 0; i < totaal; i++)
//{
//
// cout << find[i] << '\t' << find[i][0] << endl;
//
// if (word == find[i][0])
// {
// cout << "i is " << i << endl;
// cout << "j is " << j << endl;
// cout << "Calculated i and j\n";
// found[j] = find[i];
// cout << "found[j] " << found[j] << "\nfind[i] " << find[i] << endl;
// j++;
// countIn++;
// cout << "Inside if\n";
// }
// cout << "outsidenside if\n";
//}
*t = *total;
*w = *count;
//cout << countIn << endl << totaal << endl;
//cout << *count << endl << *total<<endl;
return found;
}
void displayOutput(int total, int count, string wordlist[])
{
cout << "Total words in the file: " << total;
if (count != 0)
{
cout << "\nTotal " << count << " related words found in the file\n";
for (int i = 0; i < count; i++)
cout << i + 1 << "\t" << wordlist[i] << endl;
}
else
cout << "No matching case found\n";
}
int main()
{
string nameoffile;
string wordtofind;
string *ptr1 = &nameoffile;
string *ptr2 = &wordtofind;
string foundwords[] = { "" };
int occur = 0,
totalWords = 0;
int *occ = &occur;// occurence of the certain word
int *tot = &totalWords;// total wods in the file
getUserInput(ptr1, ptr2);
processFile(nameoffile, wordtofind, occ, tot, foundwords); //calling the processing function
displayOutput(occur, totalWords, foundwords);
return 0;
}
(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}
I need to store an array of integers from a text file, but I can't find what I need to do for it exactly. I think I have the basis of the code set up, but I think I need to convert the elements into integers or something?
My output is my list :
50
0
20
10
18
-5
15
22
34
-1
But my "sorted" list ends up being -1, and a series of large negative numbers.
I troubleshooted it to being something wrong with the array.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array1[30];
int counter=0,n=0;
fstream datafile;
void bubbleSort(int list[], int length);
void selectionSort(int list[], int length);
/////////////
datafile.open("data.txt");
if (!datafile.is_open())
{
cout << "Failure to open." << endl;
return 0;
}
while (!datafile.eof()) {
datafile >> array1[counter];
n++;
cout << array1[counter] << endl;
}
datafile.close();
//////////////////////////////
//bubbleSort(array1, n);
//selectionSort(array1, n);
for (int i = 0; i < n; i++)
cout << array1[i] << ", ";
system("pause");
return 0;
}
Never use eof(), since it leads to wrong programs. See https://stackoverflow.com/a/5837670 for the reason.
while (n < 30 && datafile >> array1[n]) {
cout << array1[n] << endl;
n++;
}
{
int excess;
if (datafile >> excess) {
cerr << "error: data file too large\n";
return;
}
}
That way, the n will be correct at the end of the program.
Your code is all good except :
while (!datafile.eof()) {
datafile >> array1[counter];
n++;
cout << array1[counter] << endl;
}
It should be:
while (!datafile.eof()) {
datafile >> array1[n];
if ( datafile.fail() ) break;
cout << array1[n] << endl;
n++;
}
Only a single index variable(n) is required to parse/store into a 1D array.
The increment statement n++ in a while should always be the last one so that you are working on the current element and not the next.
Code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array1[30];
int n=0;
fstream datafile;
void bubbleSort(int list[], int length);
void selectionSort(int list[], int length);
/////////////
datafile.open("data.txt");
if (!datafile.is_open())
{
cout << "Failure to open." << endl;
return 0;
}
while (!datafile.eof()) {
datafile >> array1[n];
if (datafile.fail()) break;
cout << array1[n] << endl;
n++;
}
datafile.close();
for (int i = 0; i < n; i++)
cout << array1[i] << ", ";
system("pause");
return 0;
}
I'm trying to store hexadecimal values into some form of an array from a file then change those numbers to binary. So far the program I wrote is only collects the last value. The file looks something like this. note(a 1 or 0 is before each hex value)
1 408ed4
0 10019d94
0 408ed8
1 10019d88
0 408edc
0 1001322
My code is #include
#include <fstream>
#include <string>
#include <cstdlib>
#include <bitset>
#include <sstream>
#define MAX_ADDRESSES 1000000
using namespace std;
int main(int argc, char **argv) {
//Declare variables
int szL1 = atoi(argv[2]);
int szL2 = atoi(argv[4]);
string type = argv[6]; //Determines the type of cache
//string fileN = argv[7];
int info, i = 1, j = 1; //info is what is read in, i & j are testing variables
string *rd_add = new string[MAX_ADDRESSES]; //set the max string length for what's read
string *wrt_add = new string[MAX_ADDRESSES]; //set the max string length for what's written
int total = 0; //total # of reads/writes
int rds = 0; //base # of reads
int wrt = 0; //base # of writes
int array_size = 1001024;
char *array = new char[array_size];
int position = 0;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof() && position < array_size){
fin.get(array[position]);
position++;
}
array[position - 1] = '\0';
for (int x = 0; array[x] != '\0'; i++){
cout << array[i];
}
}
else{
cout << "File could not be opened" << endl;
}
//check for a power of 2 for szL1
while (1)
{
if (i == szL1)
break;
//Error Message
else if (i > szL1)
{
cout << "Error. sizeL1 must be a power of 2. Please try again." << endl << endl;
return 0;
}
i *= 2;
}
//cout << "size1 " << szL1 << endl;
//check for a power of 2 for szL2
while (1)
{
if (j == szL2)
break;
//Error
else if (j > szL2)
{
cout << "Error. sizeL2 must be a power of 2. Please try again." << endl << endl;
return 0;
}
j *= 2;
}
//cout << "size2 " << szL2 << endl;
//Check to see if szL2 is larger than szL1
if (szL2 <= szL1)
{
cout << "Error. sizeL2 must be larger than sizeL1. Please try again." << endl << endl;
return 0;
}
//Read file contents*****
while (cin >> info) //check this part
{
//If it is a 1, increment read files
if (info == 1)
{
cin >> rd_add[i++];
rds++;
}
else if (info == 0)
{
cin >> wrt_add[j++];
wrt++;
}
else
{
continue;
}
}
total = rds + wrt;
//Print the arguments read
cout << endl << "Input Parameters read:" << endl;
cout << "SizeL1: " << szL1 << endl;
cout << "SizeL2: " << szL2 << endl;
cout << "Type: " << type << endl;
//Print file stats
cout << endl << "Memory References Read from File" << endl;
cout << "Total: " << total << endl;
cout << rds << " Reads" << endl;
cout << wrt << " Writes" << endl;
return 0;
}
If you want to get only the hexadecimal values in a vector and your file is as you said you can just do it as below:
String hexValue, dummy;
Vector<String> hexValueVector;
ifstream fin("big_trace.txt");//open big trace file********
if (fin.is_open()){
cout << "File opened successfully" << endl;
while (!fin.eof()){
fin >> dummy >> hexValue;
hexValueVector.push_back(hexValue);
....//your remaining code
Do not forget to include the Vector library.
#include <vector>
Hope this will help you.
EDITED:
if you need the dummy too you have just to put both values in a structure:
struct myStructure{
String dummy;
String hexValue;
};
and instead of creating a vector of string you create a vector of myStructure:
Vector<myStructure> myStructureVector;
to fill your vector you have just to do this:
myStructure myStructure;
if(fin.is_open()){
...
while (!fin.eof()){
fin >> myStructure.dummy >> myStructure.hexValue;
myStructureVector.push_back(myStructure);
If this solves your problem, please vote for the answer.
About Vector, it is a STL container, if you want more details about it check http://www.cplusplus.com/reference/vector/vector/
I am coding a program that allows the user to name a file and open or create that file. Then they are able to read the info from that file in different ways or write more info into the file. The problem is that when I choose an option to read the file it first reads it fine then when I try to read it a different way it has two sets of numbers, as if it is reading the file twice.
I am unable to pin point the problem to any one function, and it is hard the explain the problem so I am posting the whole program. if you could help that would be great. Thank you in advance.
#include <ctime>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(), f1(), f2(), f3(), f4(), f5(), f6(), f7();
string file;
const int NUM_DATA = 50;
double data[NUM_DATA], temp;
int num = 0;
int main()
{
int choice;
do
{
system ("cls");
cout << " ** MENU ** \n\n";
cout << "Current Data File: " << file << "\n\n";
cout << "(1) Select/Create data file (.txt file extension will be added automatically)\n";
cout << "(2) Display all the numbers, total and average\n";
cout << "(3) Display all the numbers from smallest to the largest\n";
cout << "(4) Select a number and display how many times it shows up\n";
cout << "(5) Display the largest number\n";
cout << "(6) Append random number(s)\n";
cout << "(7) Exit the program\n\n";
do
{
cout << "Choice: ";
cin >> choice;
cout << endl;
}
while (choice < 1 || choice > 7);
switch (choice)
{
case 1: f1();
break;
case 2: f2();
break;
case 3: f3();
break;
case 4: f4();
break;
case 5: f5();
break;
case 6: f6();
break;
}
}
while (choice != 7);
return 0;
}
// Select file
int f1()
{
cout << "Name of data file: ";
cin >> file;
file = file + ".txt";
ifstream fileI;
fileI.open(file.c_str());
if(!fileI)
{
cout << "\nFile not found, creating file. \n\n";
ofstream fileO;
fileO.open(file.c_str());
fileO.close();
}
else
{
cout << "\nFile successfully read. \n\n";
fileI.close();
}
system("pause");
return 0;
}
// Display all the numbers, the total and the average
int f2()
{
f7();
ifstream fileI;
fileI.open(file);
double total = 0;
double average;
for (int count = 0; count < num; count++)
{
total += data[count];
cout << data[count] << endl;
}
average = total / num;
cout << "Total: " << total << endl;
cout << "Avearage: " << average << "\n\n";
fileI.close();
system("pause");
cin.ignore();
return 0;
}
// Display all the numbers from smallest to largest
int f3()
{
f7();
ifstream fileI;
fileI.open(file);
for(int i = 0; i < num; i++)
{
for(int j = 0; j < num; j++)
{
if(data[i] < data[j])
{
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
for (int count = 0; count < num; count++)
{
cout << data[count] << "\n\n";
}
fileI.close();
system("pause");
return 0;
}
// Display how many times a number shows up
int f4()
{
f7();
ifstream fileI;
fileI.open(file);
int numb, times = 0;
cout << "Search number: ";
cin >> numb;
cout << endl;
for (int count = 0; count < num; count++)
{
if (numb == data[count])
{
times ++;
}
}
cout << numb << " ocurrs " << times << " times." << "\n\n";
fileI.close();
system("pause");
return 0;
}
// Display the largest number
int f5()
{
f7();
ifstream fileI;
fileI.open(file);
int large = data[0];
for (int count = 0; count < num; count++)
{
if (large < data[count])
{
large = data[count];
}
}
cout << "Larget number: " << large << "\n\n";
fileI.close();
system("pause");
return 0;
}
// Append one or more random numbers
int f6()
{
ofstream fileO;
fileO.open(file, ios::app);
int rndm, numbs;
srand(time(NULL));
cout << "Add how many numbers: ";
cin >> rndm;
cout << endl;
for (int count = num + 1; count <= num + rndm ; count++)
{
numbs = (rand()%50+1);
fileO << numbs << endl;
}
cout << "Data succesfully written.\n\n";
fileO.close();
system("pause");
return 0;
}
//Array function
int f7()
{
ifstream fileI;
fileI.open(file);
fileI >> temp;
while (num < NUM_DATA && !fileI.eof())
{
data[num] = temp;
++num;
fileI >> temp;
}
fileI.close();
return num;
}
It's because, in f7(), you use num from it's last known value, rather than resetting it.
That means you're simply tacking another copy of the file on to the end of the array each time.
And, please, if you value the sanity of the people who may have to maintain your code, don't use function names like fN(), they're supposed to be readable :-)
Interestingly enough, this only affects the functions that use the array. I notice that your function which gives you the total and average reads the file itself, despite calling f7() to read it into the array. You may want to choose one method and stick with it.