C++ numbers in a file to a array - c++

Im working on a program to take a input file, sort it and print the output. These input files will have 10 , 100, 1000 or 100000 lines which each have a number per line.
Right now, my code only works for the first 10 lines.
the main part is
int array[10];
int size;
size = sizeof array/sizeof(int);
and
if(file.is_open())
{
for(int i = 0; i < size ; ++i)
{
file >> array[i];
}
}
to read the lines of the file into the array.
How can i change this to take variable lengths of file line sizes and read it into a array.
#include<iostream>
#include<string>
#include<fstream>
#include<vector>
#include<ctime>
using namespace std;
void insertion_sort(int x[],int length)
{
int key,i;
for(int j=1;j<length;j++)
{
key=x[j];
i=j-1;
while(x[i]>key && i>=0)
{
x[i+1]=x[i];
i--;
}
x[i+1]=key;
}
}
int main()
{
int array[10];
int size;
size = sizeof array/sizeof(int);
int x;
char name[256];
string sort, order, dup;
cout << "enter a file\n";
cin >> name;
ofstream ofile;
ifstream file(name);
if(file.is_open())
{
for(int i = 0; i < size ; ++i)
{
file >> array[i];
}
}
else{
cout << "file doesnt exist";
return 1;
}
size = sizeof array/sizeof(int);
cout << "enter a sort method - type insertion_sort or merge_sort or quick_sort or counting_sort\n";
cin >> sort;
cout << "Type 'dec' for non decreasing or 'inc' for increasing order\n";
cin >> order;
cout << "Type yes or no to remove duplicates\n";
cin >> dup;
if (sort == "insertion_sort")
{
insertion_sort(array,size);
cout << "\ninsertion sort";
}
if (order == "dec" )
for(int i=0;i<size/2;i++)
swap(array[i],array[size-i-1]);
if(dup == "yes")
{
int i, j;
int NewLength = 1;
for(i=1; i< size; i++){
for(j=0; j< NewLength ; j++)
{
if(array[i] == array[j])
break;
}
if (j==NewLength )
array[NewLength++] = array[i];
}
}
cout<<endl<<"sorted "<<endl;
for(x=0;x<size;x++)
{
cout<<array[x]<<endl;
}
return 0;
}

For starters, you should be using std::vector and std::string instead of static arrays. Once you switch your code to use a vector, pulling in a file of integer data is as simple as:
std::ifstream fin("myfile.dat");
std::vector<int> myVec;
std::copy(std::istream_iterator<int>(fin), std::istream_iterator<int>(), std::back_inserter(myVec));
Which also makes the output fairly simple:
std::ofstream fout("myNewFile.dat");
std::copy(myVec.begin(), myVec.end(), std::ostream_iterator<int>(fout, " "));

Something like
std::vector<int> vec;
int x;
while (file >> x)
{
vec.push_back(x);
}
might simplify your life.

Related

Sorting out int variables from a .txt file (fstream, c++)

I have a .txt file with these this line on the top '12 4 25 257' each of the numbers spaced out by a ' ' and the line ends with '\n'
I have these variables and a function getFirstLine:
int A;
int B;
int C;
int D;
ifstream File("a.txt");
void getFirstLine(int &A, int &B, int &C, int &D)
{
int list[] = {A, B, C, D};
string myText;
getline(File, myText);
int size = myText.size();
cout << size;
for (int i = 0; i < size; i++)
{
if (myText[i] != ' ')
{
list[i] = (int)myText[i] - 48;
cout << list[i] << endl;
}
}
}
I want to basically save the first number on A, second on B, third C etc...
I cant seem to get this working sadly :(
Can someone help me with this?
Output should look like:
A = 12,
B = 4,
C = 25,
D = 257,
Maybe something like this?
std::string line;
std::getline(file, line);
line = line.substr(1, line.length() - 2);
std::istringstream iss(line);
iss >> A >> B >> C >> D;
#include<iostream>
#include<vector>
#include<ifstream>
using namespace std;
struct pairs
{
char ch;
int value;
};
int main()
{
vector<pairs> store;
ifstream is("koord.txt");
pairs temp;
char ch = 'A';
while (is)
{
temp.ch = ch;
is >> temp.value;
store.push_back(temp);
}
for (int i = 0; i < store.size(); ++i)
{
cout << store[i].ch << " " << store[i].value << endl;
}
return 0;
}
you can use this. But if you read more entries char will overflow. you can use string instead of char.
This is what I ended up doing, might not be the most efficient way of doing it but it seems to work. But I will look into std::istringstream. It seems like good way to do it.
void getFirstLine(int &A, int &B, int &C, int &D)
{
string myText;
string temp;
vector<int> save;
int size = myText.size();
getline(File, myText); //get the first line of text not including \n
for (int i = 0, j = 0, size = myText.length(); i < size; i++)
{
temp.push_back(myText[i]); //adds the myTest[i] to the end of temp
if (myText[i] == ' ')
{
save.push_back(stoi(temp)); //stoi(temp) to an int --> push_back appened to save at the end
j++;
temp.clear();
}
if (i == (size - 1)) //because the end of the line doesnt have a space
{
save.push_back(stoi(temp));
j++;
temp.clear();
}
}
for (int i = 0; i < 5; i++){
cout << "list "<< i << ": "<< save[i] << endl;
}
//retruning the values
A = save[0];
B = save[1];
C = save[2];
D = save[3];
}

C++ code Runtime error on 2D array declaration

I dont understand why is this code giving runtime error on input of any test case (size of string is n, and then string is input). Not even the word "CHECK" (in the solve() function) gets printed.. Please help!
The problem link is : problem
#include <bits/stdc++.h>
using namespace std;
int a[1000][26];
int mov(int l, int u, int x)
{
if(l==u)
{
if(a[l][x]-a[l-1][x]==1)
return 1;
else
return 0;
}
int m=(l+u)/2;
return max(mov(l,m,x+1)+a[u][x]-a[m][x],mov(m,u,x+1)+a[m][x]-a[l-1][x]);
}
void solve()
{
int i,k,j,n;
string str;
cin >> n >> str;
cout << "CHECK";// This is not getting printed
for(i=0;i<26;i++)
a[0][i]=0;
for(i=1;i<n+1;i++)
{
for(j=0;j<26;j++)
{
a[i][j]=a[i-1][j];
if(str[i-1]==j+'a')
a[i][j]++;
}
}
k=mov(1,n,0);
cout << n-k << "\n";
}
int main()
{
int t=1;
cin >> t;
while(t--)
solve();
}
Your very first input shows how many input "pairs" will be given. In your case, you have skipped this part and gone into gathering the input "pairs". This is why "CHECK" wont get printed. To resolve this, have a cin to capture the number of input pairs, then iterate through the inputs to get the pair.
void solve()
{
int i, k, j, n;
string str;
memset(a[0], 0, sizeof(int) * 26); // Use this instead.
cin >> n;
cout << "CHECK";
for (i = 1; i < n + 1; i++)
{
cin >> j >> str;
for (j = 0; j < 26; j++)
{
a[i][j] = a[i - 1][j];
if (str[i - 1] == j + 'a')
a[i][j]++;
}
}
k = mov(1, n, 0);
cout << k << "\n";
}
Also, try not to use using namespace std;.

how to create an array of Bitset in c++

I want to create an array of Bitset .Binary Bitset(example "100","1010",etc)
After that I want to input from user and store in the the Bitset .
I have tried the following line but it says error.
#include<bits/stdc++>
using namespace std;
int main()
{
int n,i;
string bit_string;
cin>>n // size of Bitset array.
bitset<8> brr[n];//
for(i=0;i<n;i++)
{
cin>>bit_string;
brr[i](bit_string);
}
return 0;
}
I want to create n Bitset each of size 8 bits.Where n is given by user.
my input is binary string like.
"110010","001110"
please help
The error ocurrs because you are trying to creat a C-style array using n which is not compile-time constant. It's not possible to creat a C-style array without being n known at compile time.
The following is a good way to do what you want
Creat a std::vector<std::bitset<8>> to hold your bitset<8>s, as follows.
Note that the code ignores the excess of characters in strings iput like "111111110" (makes it "11111111") and treats any character except '1' as if it were '0' and if the input string is less than 8 characters, the code adds zeros by the default of the bitsets
#include <vector>
#include <bitset>
#include <iostream>
int main() {
int n, i;
std::string bit_string;
std::cout << "Enter the size";
std::cin >> n; // size of Bitset array.
std::vector<std::bitset<8>> brr(n);//
for (i = 0; i < n; i++) {
std::cin >> bit_string;
for (int j{}; j < bit_string.size() && j < 8; ++j) {
brr[i][j] = (bit_string[j] == '1') ? 1 : 0;
}
}
//To test
for(auto const& el :brr)
{
for(int i{}; i < 8;)
std::cout << el[i++];
std::cout<<"\n";
}
}
See Why is "using namespace std;" considered bad practice?
and
Why should I not #include <bits/stdc++.h>?
For dynamic count of the objects , Please try vector<> instead of array[]
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
vector<bitset<8>> arr; //size()=>0
arr.resize(n); //size()=>n
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
return 0;
}
If you still want to use array , please try this way
#include<bits/stdc++>
using namespace std;
int main()
{
int n, i;
string bit_string;
cin >> n; // size of Bitset array.
bitset<8>* arr = new bitset<8>[n];
for (i = 0; i < n; i++)
{
cin >> bit_string;
bitset<8>& br = arr[i]; //get the i of n
int maxlen = 8;
if (bit_string.size() <= 8)
maxlen = bit_string.size();
else
cout << "warning invalid len " << bit_string.size() << " of " << bit_string << endl;
for (int j = 0; j < maxlen; j++)
{
if (bit_string[j] == '1')
br.set(j, true);
}
//cout << endl << br << endl; //output test
}
delete[] arr; //IMPROTAND , delete the array and free memory
return 0;
}

Adding int's from txt file to vector in 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;

C++ line.exe has stopped working

I make some program in C++ which in matrix finds longest horizontal line of 0s.
In first line I input n and m (rows and columns in matrix array a), and later array. Main problem is when I insert first line (all correct with it) the program stops with error -1073741510, line.exe has stopped working.
#include <iostream>
using namespace std;
int main()
{
int n, m;
cin >> n, m;
int a[n][m];
int i,j,k;
for (i=0;i<n;i=i+1){
for(j=0;j<m;j=j+1){
int temp;
cin >> temp;
a[i][j] = temp;
}
}
int max;
for (i=0;i<n;i++){
for(j=0;j<m;j++){
if(a[i][j]==0){
for(k=j+1;k<m;k++){
if(a[i][k]==0){
max++;
}else{break;}
}
}
}
}
cout << max;
return 0;
}
Sorry for big amount of for loops, I don't know better way of solving problem.
To read both numbers n and m use:
cin >> n >> m;
Otherwise, as you have cin >> n, m; it is equivalent with
cin >> n;
m; // This has no effect
For a solution to the correct operation of your algorithm, try this:
int maxZeros = 0;
int lineContainingMaxZeros = 0;
for (i = 0; i < n; i++) {
int countZero = 0;
for (j = 0; j < m; j++) {
if (a[i][j] == 0)
countZero++;
}
if (countZero > maxZeros) {
maxZeros = countZero;
lineContainingMaxZeros = i;
}
}
cout << "Line: " << lineContainingMaxZeros << " containing " << maxZeros << " zeros";