Adding int's from txt file to vector in c++ - c++

Writing a program that reads a txt file, inputs the values into a vector, then determines the number of values (temperatures) that are below freezing. I keep getting 0 as the result and can't figure out what I have wrong. Any help would be greatly appreciated!
Below is the actual assigned question and my code so far
Write a main program that asks the user for a file name. The file contains daily temperatures (integers).
The main calls the two functions to (1) store temperatures in the vector (2) display the number of days with freezing temperatures (<= 32o F).
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
using namespace std;
//prototypes
void readTemperaturesFromFile(vector<int>& V, ifstream&);
int countFreezingTemperatures(vector<int>& V);
int main()
{
ifstream ins;
string fileName;
int totalFreezing = 0;
vector<int> temperature;
cout << "Please enter the name of the file: ";
cin >> fileName;
ins.open(fileName.c_str());
readTemperaturesFromFile(temperature, ins);
totalFreezing = countFreezingTemperatures(temperature);
cout << "Total number of days with freezing temperature: " << totalFreezing <<
endl;
ins.close();
system("pause");
return 0;
}
// The function reads temperatures (integers) from a text file and adds
// pushes them to the vector. The number of integers in the file is
// unknown
void readTemperaturesFromFile(vector<int> &V, ifstream& ins)
{
int temperature, v;
while (ins >> v)
{
V.push_back(v);
}
}
// The function returns the number of freezing temperatures (<=32oF)
// in the vector.
// You need to consider the case where the vector is empty
int countFreezingTemperatures(vector<int>& V)
{
int counter = 0;
if (V.empty());
cout << "empty" << endl;
for (int i = 0; i < V.size(); i++)
if (V[i] <= 32)
{
return counter;
counter++;
}
}

You need to change countFreezingTemperatures function
There is unnecessary ; after if
You should count all the temperature <=32oF and then return the counter
int countFreezingTemperatures(vector<int>& V)
{
int counter = 0;
if (V.empty())
{
cout << "empty" << endl;
}
else
{
for (int i = 0; i < V.size(); i++)
{
if (V[i] <= 32)
{
counter++;
}
}
}
return counter;
}

Your countFreezingTemperature implementation is returning 0. Take a look:
for (int i = 0; i < V.size(); i++)
if (V[i] <= 32)
{
return counter;
counter++;
}
}
This code is saying "immediately upon reaching a temperature at/under 32, return counter" (which is set to 0).
Here's a fix:
for (int i = 0; i < V.size(); i++)
if (V[i] <= 32)
{
counter++;
}
}
return counter;

Related

Why is the Vector array printing the memory addresses instead of the array values and why do I get an access violation in my sorting functions? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm developing a program that reads text files and stores the words in an array that can be sorted and then searched through. I've already tried using a dynamically allocated array to place the words into from the text files, but all I get is string cannot be read error from my getline (this doesn't happen when I use vectors). When I try to print out the vector array to see what is being passed through to my sorting functions, it prints out the memory addresses of the array and not the values stored in the array.
I also get a read access violation in my sorting functions at certain points in the function after I've pass the vector arrays to them and I don't understand why. I do show in the code where the problem is accruing. Please note that I'm very new to coding and this program is far from complete. I'm including all of the code I have done so far because if I just show the problem areas I don't think it will be understandable why I'm having these errors. Any help is appreciated thank you.
#include "flore0900header.h"
int main()
{
string name;
int num = 0, num2 = 0, count = 0;
vector<string> word; //to pass vector array to another function
cout << "Hello. Enter your name: ";
cin >> name;
cout << endl;
cout << "Welcome " << name << " This program lets you test 5 different sorting algorithms using texts files" << endl;
cout << endl;
cout << "Which text file would you like to search?" << endl;
cout << "=========================================" << endl;
cout << "1. The Blue Hotel" << endl;
cout << "2. 20,000 Leagues Under the Sea" << endl;
cout << "3. A Tale of Two Cities" << endl;
cin >> num;
count = text_select(num);
catch_array(&word); //passing vector array by reference. '&' is there because it won't work otherwise
cout << endl;
cout << "Which sorting algorithems would you like to use?" << endl;
cout << "========================================" << endl;
cout << "1. Selection" << endl;
cout << "2. Bubble" << endl;
cout << "3. Insertion" << endl;
cout << "4. Merge" << endl;
cout << "5. Quick" << endl;
cin >> num; cin >> num2;
sort_select(num, &word, count);//'&' is there because it won't work otherwise
sort_select(num2, &word, count);//'&' is there because it won't work otherwise
cout << endl;
cout << "Ok! Running algorithms..........." << endl;
}
the header file
#ifndef FLORE0900HEADER_H
#define FLORE0900HEADER_H
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <istream>
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
#include <ostream>
/* some of the includes are not needed, I haven't removed the un-needed ones yet*/
using std::cout;
using std::cin;
using std::endl;
using std::string;
using std::vector;
void selection_sort(vector<string> a[], int size);
void bubble_sort(vector<string> a[], int size);
void insertion_sort(vector<string> a[], int size);
void merge_sort(vector<string> a[], int from, int to);
void quick_sort(vector<string> a[], int from, int to);
int text_select(int num);
void sort_select(int num, vector<string> a[], int size);
vector<string> catch_array(vector<string> a[]);
void merge(vector<string> a[], int from, int mid, int to);
int min_position(vector<string> a[], int from, int to);
int partition(vector<string> a[], int from, int to);
void swap(int& x, int& y);
void print(vector<string> a[], int size);
#endif
text_select function file
#include "flore0900header.h"
//#include <vector>
int text_select(int num)
{
int count = 0;
vector<string> words(100000);
//vector<string>* word2 = new vector<string>[count];
std::ifstream infile;
if (num == 1)
{
infile.open("blue_hotel.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);//string read error when using not using vector
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else if (num == 2)
{
infile.open("2under.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else if (num == 3)
{
infile.open("2city10.txt");
if (infile.is_open())
{
cout << "file is open" << endl;
getline(infile, words[count]);
while (!infile.eof())
{
infile >> words[count];
count++;
infile.ignore();
getline(infile, words[count]);
}
}
else
{
cout << "file didn't open" << endl;
exit(1);
}
}
else
cout << "not a valid choice try again" << endl;
infile.close();
catch_array(&words);//if I don't use '&' the vector won't pass through
return count;
}
vector<string> catch_array(vector<string> a[])
{
return *a;//if I don't put '*' before the 'a' I get an error
}
sort_select file
#include "flore0900header.h"
void sort_select(int num, vector<string> a[], int size)
{
int from = 0;
if (num == 1)
{
selection_sort(a, size);
}
else if (num == 2)
{
bubble_sort(a, size);
}
else if (num == 3)
{
insertion_sort(a, size);
}
else if (num == 4)
{
merge_sort(a, from, size);
}
else if (num == 5)
{
quick_sort(a, from, size);
}
else
cout << "not a valid pick try again" << endl;
}
selection_sort file
#include "flore0900header.h"
void selection_sort(vector<string> a[], int size)
{
int next;
for (next = 0; next < size - 1; next++)
{
print(a, size);//to see what is being passed to the function
int min_pos = min_position(a, next, size - 1);
swap(a[next], a[min_pos]);
}
}
int min_position(vector<string> a[], int from, int to)
{
int min_pos = from;
for (int i = from + 1; i <= to; i++)
{
if (a[i] < a[min_pos])//read access violation happens here
{
min_pos = i;
}
}
return min_pos;
}
void print(vector<string> a[], int size)
{
for (int i = 0; i < size; i++)
{
cout << &a[i] << " ";//is printing memory locations instead of values
}
cout << endl;
}
bubble_sort file
#include "flore0900header.h"
void bubble_sort(vector<string> a[], int size)
{
for (int i = 0; i < size - 1; i++) //loop for recording no# of iteration needed to complete the sorting
{
int flagForSwap = 0; //creates a flag variable that accounts for wheather the swap function is called at all
//loop for counting comparisons
for (int j = 0; j < size - 1 - i; j++)
{
if (a[j] > a[j + 1]) //(read access violation happens here) compare adjacent array elements
{
swap(a[j], a[j + 1]); //completes the swap
flagForSwap = 1; // flag to 1 if swap is used
}
}
if (flagForSwap == 0) //breaks the iteration loop if inputed array is already sorted and no swap is needed
{
break;
}
}
}
void swap(int& x, int& y)
{
int temp = x; //creates a temp variable to store the value of the current element
x = y; // change the value of the current element to next element
y = temp; //assigns the value of temp to next element
}
insertion_sort file
#include "flore0900header.h"
void insertion_sort(vector<string> a[], int size)
{
for (int i = 1; i < size; i++)
{
vector<string> next = a[i];//read access violation happens here
int j = i;
while (j > 0 && a[j - 1] > next)
{
a[j] = a[j - 1];
j--;
}
a[j] = next;
}
}
merge_sort file
#include "flore0900header.h"
void merge_sort(vector<string> a[], int from, int to)
{
if (from == to)
{
return;
}
int mid = (from + to) / 2;
merge_sort(a, from, mid);
merge_sort(a, mid + 1, to);
merge(a, from, mid, to);
}
void merge(vector<string> a[], int from, int mid, int to)
{
int n = to - from + 1;
vector<string>* b = new vector<string>[n];
int i1 = from;
int i2 = mid + 1;
int j = 0;
while (i1 <= mid && i2 <= to)
{
if (a[i1] < a[i2])//read access violation happens here
{
b[j] = a[i1];
i1++;
}
else
{
b[j] = a[i2];
i2++;
}
j++;
}
while (i1 <= mid)
{
b[j] = a[i1];
i1++;
j++;
}
while (i2 <= to)
{
b[j] = a[i2];
i2++;
j++;
}
for (j = 0; j < n; j++)
{
a[from + j] = b[j];
}
delete[] b;
}
quick_sort file
#include "flore0900header.h"
void quick_sort(vector<string> a[], int from, int to)
{
if (from >= to)
{
return;
}
int p = partition(a, from, to);
quick_sort(a, from, p);
quick_sort(a, p + 1, to);
}
int partition(vector<string> a[], int from, int to)
{
vector<string> pivot = a[from];
int i = from - 1;
int j = to + 1;
while (i < j)
{
i++;
while (a[i] < pivot)//read access violation happens here
{
i++;
}
j--;
while (a[j] > pivot)
{
j--;
}
if (i < j)
{
swap(a[i], a[j]);
}
}
return j;
}
There is no such thing as "a vector array".
You can have arrays of vectors, but you don't.
Yet, here, your function is written as if it does:
int partition(vector<string> a[], int from, int to)
// ^^
I imagine this was done because, before you added the [] here and the & there, your functions appeared not to do anything.
That was because you were passing the vector by value, so changes in the function were made to a copy, and thus not reflected in the calling scope.
Your changes allowed the code to compile, and possibly even "work" in some obscure cases, but only by chance; the [INDEX] syntax is shared between vectors and arrays. But you don't have an array, so pretending to the function that you do is wrong. Most of your accesses go out of bounds.
Also note that if you didn't have a bool operator<(const vector<string>&, const vector<string>&) defined somewhere, it wouldn't compile.
Anyway, the solution to use your one vector is simple:
Get rid of that []
Get rid of that &
Change what is now vector<string> into vector<string>&. That & means "take a reference".

Square Root Code C++ without sqrt()

I have to create a code where the user inputs a number which is a perfect square, and I have to show its root. I've made this code, but I'm getting Segmentation Fault 11 , in this piece: int j = squareRootVector[i];
squareRoot.push_back(j);.
I can't change the code too much, so is there a way that I can do that?
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout <<
"Enter the number:\n";
int input;
int number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
cin >> number;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
cout << number << endl;
squareRootVector.push_back(divider);
}
}
for(int i = 0; i < squareRootVector.size(); i++) {
cout << squareRootVector[i] << " ";
/*******PROBLEM*******/
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
/*********************/
}
int root;
for (int i = 0; squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is: " << root << endl;
return 0;
}
The behaviour on accessing squareRootVector[i+1] with i just one below size (which your loop constaint allows) is undefined.
Consider writing
for (std::size_t i = 1; i < squareRootVector.size(); i++) {
instead, and rebasing the for loop body accordingly. I've also slipped in a change of type for i.
Shortly, the problem is that the last cycle in the last "for":
for(int i = 0; i < squareRootVector.size(); i++)
has the following line in it:
squareRootVector[i] == squareRootVector[i+1];
This is an "out of limits" error: squareRootVector only has squareRootVector.size() elements (let's say n), and the elements are indexed from 0 to n-1.
squareRootVector[i+1] in the last cycle points one element after the last one of squareRootVector, which is undefined behavior.
Using vector::iterator is proper way.
for(vector<int>::iterator it = squareRootVector.begin(); it != squareRootVector.end(); ++it)
{
if( (it+1) == squareRootVector.end() )
{
//what to do if there's no next member???
break;
}
if( *it == *(it+1) )
{
squareRoot.push_back(*it);
}
}
Thanks for the answers, guys. I've ended up with this code:
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "Enter the number:\n";
int input = 0;
int number = 0;
cin >> input;
number = input;
int divider = 2;
vector<int> squareRootVector;
vector<int> squareRoot;
for(int divider = 2; number > 1; divider++) {
while((number % divider) == 0) {
number /= divider;
squareRootVector.push_back(divider);
}
}
int vectorSize = squareRootVector.size() - 1;
for(int i = 0; i < vectorSize; i++) {
if(squareRootVector[i] == squareRootVector[i+1]) {
int j = squareRootVector[i];
squareRoot.push_back(j);
}
}
int root = 1;
for (int i = 0; i < squareRoot.size(); i++) {
root = root * squareRoot[i];
}
cout << "Square Root of " << input << " is " << root << endl;
return 0;
}

Checking for validity in 2d array

so i am creating a sudoku validity checker program in C++. the program takes in a csv file with an already completed sudoku board. the program is supposed to read the file line by line and put the numbers into a 2d array (which it's doing just fine). i'm getting stuck on the checking whether or not there are any duplicate numbers in a row (i assume that if i can get this working then the columns should be fairly similar). i know how the algorithm is supposed to work in my head but i just can't seem to get it into code.
Algorithm:
1) look at each row and check for numbers 1 through 9 making sure that they only appear once (if at all)
2) if a duplicate is found (which means that some number is missing) tell the user at what row and column the error was found.
3) otherwise move on to the next row and do it again
i think that it's supposed to be a for loop running this but it's been a long time since i've coded in C++ and nothing on the internet has been very helpful to me.
Any help is appreciated.
Here is my code so far:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <thread>
using namespace std;
int *board[9];
int row, col;
void printBoard();
void is_row_ok();
int main()
{
for (int i = 0; i < 9; ++i)
{
board[i] = new int[9];
}
printBoard();
is_row_ok();
cout << endl;
return 0;
}
void printBoard()
{
string line;
string val;
ifstream myFile("Testfile1.txt");
for (int row = 0; row < 9; ++row)
{
string line;
getline(myFile, line);
if (!myFile.good())
break;
stringstream iss(line);
cout << endl;
for (int col = 0; col < 9; ++col)
{
string val;
getline(iss, val, ',');
if (!iss.good())
break;
stringstream convertor(val);
convertor >> board[row][col];
cout << board[row][col] << " ";
}
}
cout << endl;
cout << endl;
}
void is_row_ok()
{
bool found = false;
int i, j;
for (int i = 0; i < 10; ++i) //<------ edit starts here
{
int counter = 0;
for (int j = 0; j < 9; ++j)
{
if(board[row][j] == i)
{
cout << "Before " << counter << endl;
counter++;
cout << counter << endl;
}
if(counter > 1)
break;
}
}
}
The easiest way I can think of is 2 loops (one inside of another): 1 gets you through numbers 1 to 9 and the other goes through the elements of the row. Small tip with code.
for(int i=1;i<10;i++){
int counter =0;
for(int j=0;j<9;j++){
if(board[row][j] ==i)counter ++;
}
if(counter >1) break; //here you check that there´s only one number on the row.
}
Of course, there are other ways to do it, this one is quite basic and slow.
-------------------------------------EDIT-------------------------------------------
Your function should be bool in order to know if there´s repeated number or not.
bool is_row_ok(vector<vector<int> board)//I suggest you use vectors instead of arrays.
{
//i and j are declared on for, there´s no need to declare them again.
for (int i = 0; i < 10; ++i)
{
int counter = 0;
for (int j = 0; j < 9; ++j)
{
if(board[row][j] == i)counter++;
if(counter > 1)return false;
}
}
return true;
}
Now you call this function on main. If function returns true, everything is ok, if it returns false, you have a repeated number.
int main(){
if(is_row_ok(board)cout<<"No number repeated"<<endl;
else cout << "Number repeated"<<endl;
return 0;
}
I think the easiest way is to use std::sort + std::unique as unique returns iterator to the new end of range.
#include <algorithm>
using namespace std;
int main()
{
int n[15] = { 1, 5, 4, 3, 6, 7, 5, 5, 5, 4, 2, 3, 9, 8, 9 };
int* end = n + 15;
sort(n, n + 15);
bool has_no_duplicates = (unique(n, n + 15) == end);
return 0;
}
This is just an example but you should get the idea.

Checking Duplicates Numbers In Array c++

I wrote a simple C++ program that finds how many duplicates are in the array.
This works perfectly for me but this is very long code. And I would like to know if there is any short code which may perform this task successfully:
#include<iostream>
using namespace std;
int main()
{
int a[10];
int reper=0,word=0,flage=0,number[10]={
0
};
//Getting Input From User
for (int i = 0; i <=9; i++)
{
cout<<"Enter The Value For "<<i<<" Index"<<endl;
cin>>a[i];
}
//Checking The Duplicates Numbers
for (int i = 0; i <= 9; i++)
{
reper=0;
flage=0;
for (int j = 0; j <=9; j++)
{
if (a[i]==a[j])
{
if (i!=j)
{
reper++;
}
}
}
number[i]=a[i];
for (int k = 0; k <=9; k++)
{
if (i!=k)
{
if(number[i]==number[k])
{
flage=1;
break;
}
}
}
//If There Are Duplicates Then Prints That Numebr, How Many Times It Repeated And Total Occurance Of That Number In The Array
if (reper!=0&&flage==0)
{
cout<<"Repeated Number Of The Array Is : "<<a[i]<<" ";
cout<<"And This Number Repeated "<<reper<<" Times "<<"And Total Occurance Of This Number is : "<<reper+1<<endl;
word=a[i];
}
}
//If There Is Nothing Any Duplicate In The Array Then Simply Prints This Message On Console
if (reper==0&&word==0)
{
cout<<"There Is Nothing Any Repeated Number Of This Array: "<<endl;
}
system("Pause");
return 0;
}
IMHO the easiest way to implement this - using http://en.cppreference.com/w/cpp/container/multiset. It has logarithmic complexity and inner methods to count repeated items.
Refer an example below:
#include <iostream>
#include <set>
int main(int argc, char *argv[])
{
std::multiset<int> ms;
//Getting Input From User
for (int i = 0; i <=9; i++)
{
std::cout<<"Enter The Value For "<<i<<" Index"<<std::endl;
int val;
std::cin>>val;
ms.insert(val);
}
bool repeated_number_found=false;
std::multiset<int>::const_iterator it = ms.begin();
while (it != ms.end()) {
int reper=ms.count(*it);
if (reper > 1){
std::cout << "Number " << *it << " repeated for " << reper << " times" << std::endl;
repeated_number_found=true;
}
it = ms.upper_bound(*it);
}
if (!repeated_number_found){
std::cout<<"There Is Nothing Any Repeated Number Of This Array"<<std::endl;
}
return 0;
}
But using this container you will loose first entrance of repeated number, if it matters to you, I will recommend using struct or std::pair to hold entrance number with entered number. In this case you will need to provide custom comparator also (refer to doc.)
I think the better way to achieve this would be to sort the array and do something like this :-
(include the header file algorithm before doing this.)
vector <int> a (10,0);
for (int i = 0; i <=9; i++)
{
cout<<"Enter The Value For "<<i<<" Index"<<endl;
cin>>a[i];
}
int count = 0;
sort(a.begin(), a.end());
for(int i = 0; i < a.size() - 1; i++) {
if (a[i] == a[i + 1]) {
count++;
}
}
cout << count << endl;

display wheter or not an array entered by the user is unique or not

I am new to C++ I am making an array based off of user input and displaying whether the array is unique or not. my initial thought is I have to end up creating another array to store values and then compare the elements. My code compiles without errors but does not do what I want it to do. I can't used advanced methods such as hashmaps or vectors. Any help or insight is greatly appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int myArray[6];
string name;
int i, k;
int ov = 0;
int newVal = 0;
for (int index = 0; index < 6; index++)
{
cout << "Enter number a number: ";
cin >> myArray[index];
}//end loop for
for (i = 0; i < 6; i++)
{
ov = myArray[i];
}
for (k = i + 1; k < 6; k++)
{
if (ov == myArray[k])
{
newVal = 1;
}
}
if (newVal == 1)
{
cout << "Not all unique";
}
else
{
cout << "All unique";
}
cin.get();
return 0;
}