read int per line c++ error needs solution - c++

hey guys I need help for my read code seems not working properly here's the code. The problem is as shown in the picture, the compiler are supposed to display all 1 million int value but it seems that my write or the display code was wrong. It shows nothing like it's not even reading.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
#include <omp.h>
#include <ctime>
#include <cstdlib>
using namespace std;
int* CreateArray( int*);
void shellSortParallel( int*, int);
void shellSortSequential(int*, int);
void InsertSort( int*, int, int, int);
int main()
{
int array_size = 1000000;
int n=0;
int* arr=new int[array_size];
ifstream fin("OUTPUT1.txt");
if(! fin)
{
cout << "File could not be opened." << endl;
}
else
{
cout << "File Opened successfully!!!. Reading data from file into array" << endl;
int data;
while(fin>>data)
{
arr[n] = data;
n++;
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < array_size; i++)
{
cout << arr[i];
}
}
fin.close();
int length = 1000000;
double endTime = 0, startTime = 0, totalTime = 0;
double start, end;
cout << "Program is now sorting using shell sort" <<endl;
startTime = time(NULL);
start = omp_get_wtime();// Start performance timer 1 run
shellSortParallel(arr, length);//Run the algorithm
end = omp_get_wtime();// End performance timer 1 run
endTime = time(NULL);
totalTime = endTime - startTime;
cout << "This is the time it took to run. " << totalTime << endl;// time in seconds
int stupid = 0;
cin >> stupid;
cout << "Program has completed all tasks!!" << endl;
return 0;
}
void shellSortParallel(int array[], int length)
{
int h;
int j = 0;
int temp = 0;
int i = 0;
for(h =length/2; h > 0; h = h/2)
{
#pragma omp parallel for shared( array, length, h, i) default(none)
for( i = 0; i < h; i++)
{
//int ID = omp_get_thread_num();
InsertSort(array, i, length, h);
}
}
}
void InsertSort(int arr[], int i, int length, int half)
{
//cout << ID << " ";
int temp = 0;
int j = 0;
for (int f = half + i; f < length; f = f + half)
{
j = f;
while(j > i && arr[j-half] > arr[j])
{
temp = arr[j];
arr[j] = arr[j-half];
arr[j-half] = temp;
j = j -half;
}
}
}
and here is the short version of the file that I'm going to read. Its a random number between 1 to 1million per line
2377763
88764877846
281327
60
625
86
646127818
14551
2177645
32033
1826761
555173
3415445377
32430
1101
any help would be much appreciate, thank you before

By if(fin>>data) you are not just testing, but retrieving data from stream. I suggest use ifs.good() for testing. Overall, you can write such a code instead
std::ifstream fin ("OUTPUT1.txt", std::ifstream::in);
char c = fin.get();
while (fin.good())
{
std::cout << c;
c = fin.get();
}

arr[n-1] = '\0'; is not correct because it's not an array of character so don't mind.
to correct it:
int data;
while(fin>>data)
{
arr[n] = data;
n++;
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < array_size; i++)
{
cout << arr[i];
}
why allocating such huge array of integers? use vector is a good thing:
vector<int> vec;
ifstream fin("OUTPUT1.txt");
int data;
while(fin >> data)
{
vec.push_back(data);
}
cout << "Displaying Array..." << endl << endl;
for(int i = 0; i < vec.size(); i++)
cout << vec[i] << endl;
fin.close();
88764877846 out band of an integer which causes the loop stop reading so you have to either get values as strings then convert into __int64 or __int128
to read values as strings:
string sLine;
int nLines = 0;
ifstream fin("OUTPUT1.txt");
// first read to get number of lines
while(getline(fin, sLine))
nLines++;
//create an array of strings
string* pstrValues = new string[nLines];
// set the get pointer to the beginning of file because the previous read moved it
fin.clear();
fin.seekg(0, ios::beg);
int i = 0;
while(getline(fin, sLine))
{
pstrValues[i] = sLine;
i++;
}
cout << "Displaying Array..." << endl << endl;
for( i = 0; i < nLines; i++)
cout << pstrValues[i] << endl;
fin.close();
now you have an array of strings convert it to int values but you must convert to __int64 because as I said there are values bigger than size of int (4bytes)

Related

cmd window stops working, text file is read wrong with fstream

in the function Read() when i output arrays klas[] and nauj[] everything seems to be read fine, but back in the main function they get destroyed and seem to be filled with other text file. Do you have any idea whats the problem here?
#include <iostream>
#include <fstream>
using namespace std;
const char klase[] = "klase.txt";
const char naujokai[] = "lele.txt";
void Read(int klas[], int nauj[], int &nk, int &nj);
int main()
{
int klas[] = {};
int nauj[] = {};
int nk;
int nj;
Read(klas, nauj, nk, nj);
for(int i = 0; i < nk; i++){
cout << klas[i] << endl;
}for(int i = 0; i < nj; i++){
cout << nauj[i] << endl;
}
return 0;
}
void Read(int klas[], int nauj[], int &nk, int &nj)
{
ifstream fklase(klase);
fklase >> nk;
for(int i = 0;i < nk;i++){
fklase >> klas[i];
cout << klas[i] << endl << endl;
}
fklase.close();
ifstream fnaujokai(naujokai);
fnaujokai >> nj;
for(int i = 0; i < nj; i++){
fnaujokai >> nauj[i];
cout << nauj[i] << endl << endl;
}
fnaujokai.close();
}
Zero-size arrays such as int klas[] = {}; are not standard and writing into them as you do in fklase >> klas[i]; is Undefined Behavior since they have no room to store anything. Also note that when you use int klas[] as a function argument it is actually equivalent to int * klas.

Cannot display proper percentage, or total from array in for loops

The problem I am having with my program is, first, when I calculate percent, it's not adding all the elements in the array to a total and diving them from. I tried putting the total += percents[i]; in a nested for-loop, but it just gave me negative %.
Also, my total at the end won't display anything. At first, I had it and all the function defined in the main(), but it didn't do anything. Even after the change, it doesn't work. Also, last thing, my file has 20 items, yet the loops only read in 19 items. If I change to 20, it crashes.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void inputValues(string names[], int votes[])
{
ifstream inputfile;
inputfile.open("votedata.txt");
if(inputfile.is_open())
{
for(int i = 0; i < 19; i++)
{
inputfile >> names[i] >> votes[i];
}
}
}
double *calcPercents( double percents[], int votes[], double total)
{
for(int i = 0; i < 19; i++)
{
percents[i] = votes[i];
total += percents[i];
percents[i] = (percents[i]/total)*100;
}
return percents;
}
string determineWinner(string names[], double percents[])
{
double temp = 0;
string winner;
for(int i = 0; i < 19; i++)
{
if(percents[i] > temp)
{
temp = percents[i];
winner = names[i];
}
}
return winner;
}
void displayResults(string names[], int votes[], double percents[])
{
int total = 0;
calcPercents(percents, votes, total);
cout << "Candidate Votes Received % of Total Votes " << endl;
for(int i = 0; i < 19; i++)
{
cout << names[i] << " " << votes[i] << " " << percents[i] << "%" << endl;
}
cout << "Total " << total << endl;
cout << " The winner of the election is " << determineWinner(names, percents) << endl;
}
int main()
{
string names[19], winner;
int votes[19];
double percents[19];
inputValues(names, votes);
displayResults(names, votes, percents);
}
My file is in the style:
bob (tab) 1254
joe (tab) 768
etc.
If you have to use arrays instead of std::vectors you should pass their size to the functions using them. One way is to set the size using a constant, like this:
#include <iostream>
#include <fstream>
#include <string>
using namespace std; // bad practice
const int size = 20;
void inputValues(string names[], int votes[], int n);
// add the size as a parameter of the function ^^^^
int calcPercents( double percents[], int votes[], int n );
//^^ I'll explain later why I changed your signature ^^^
string determineWinner(string names[], double percents[], int n );
void displayResults(string names[], int votes[], double percents[], int n);
int main()
{
// It's always better to initialize the variables to avoid undefined behavior
// like the negative percentages you have noticed
string names[size] ="";
int votes[size] = {0};
double percents[size] = {0.0};
inputValues(names, votes, size);
displayResults(names, votes, percents, size);
}
To calculate the percentages you can use two loops, one for the sum and the other to get the percentage. In your function you pass total as a parameter by value, so it will be copied and the changes will never be visible outside the function. I choose to return that vaule, even if doing so the name of function becomes a litle misleading:
int calcPercents( double percents[], int votes[], int n )
{
int total = 0;
for(int i = 0; i < n; i++)
// note the bound ^^^
{
total += votes[i];
}
double factor = 100.0 / total;
for(int i = 0; i < n; i++)
{
percents[i] = factor * votes[i];
}
return total;
}
You should also add some checks to the input function, I only add the size parameter. Note that having initialized the arrays, even if it fails reading the file the arrays doesn't contain random values:
void inputValues(string names[], int votes[], int n)
{
ifstream inputfile;
inputfile.open("votedata.txt");
if(inputfile.is_open())
{
for(int i = 0; i < n; i++)
{
inputfile >> names[i] >> votes[i];
}
}
}
I'd change the function which determine the winner too:
string determineWinner(string names[], double percents[], int n )
{
if ( !n )
{
return "";
}
double max = percents[0];
// update an index instead of a string
int winner = 0;
for( int i = 1; i < n; i++ )
{
if( percents[i] > max )
{
max = percents[i];
winner = i;
}
}
return names[winner];
}
For the last function, only remember to add the size:
void displayResults(string names[], int votes[], double percents[], int n)
{
int total = calcPercents(percents, votes, n);
cout << "Candidate Votes Received % of Total Votes " << endl;
for( int i = 0; i < n; i++ )
{
cout << names[i] << " " << votes[i] << " "
<< percents[i] << "%" << endl;
}
cout << "Total " << total << endl;
cout << " The winner of the election is "
<< determineWinner(names, percents,n) << endl;
}

can not swap array elements c++

I am new to C++. I am trying to solve a problem in the textbook: swap the first and last element in an array. But when I run the code I wrote, nothing happened and even the sentence "Please enter the numbers in the array: " does not show up. Anyone could give some help? Thanks.
#include <iostream>
using namespace std;
int swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
cout << "Please enter the numbers in the array: " << endl;
int input;
cin >> input;
for(int i=0; i<SIZE; i++)
{
test[i] = input;
}
swap(test, SIZE);
cout << test[SIZE] << endl;
return 0;
}
There were a few mistakes:
You should get the input inside the loop and then assign it to the test array.
When printing the swapped value, access the test array with SIZE-1 instead of SIZE, because array indexes run from 0 to SIZE-1, inclusive.
You declared swap() as returning int, but provided no return statement (this suggests that you haven't enabled enough warnings from your compiler).
#include <iostream>
using namespace std;
void swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
int input;
cout << "Please enter the numbers in the array: " << endl;
for(int i=0; i<SIZE; i++)
{
cin >> input;
test[i] = input;
}
swap(test, SIZE);
cout << test[SIZE-1] << endl;
return 0;
}
#include <iostream>
using namespace std;
//Here return type should be void as you are not returning value.
void swap(int values[], int size)
{
int temp = values[0];
values[0] = values[size-1];
values[size-1] = temp;
}
int main()
{
const int SIZE = 5;
int test[SIZE];
cout << "Please enter the numbers in the array: " << endl;
//USE LOOP TO TAKE INPUT ONE BY ONE IN AN ARRAY
for(int i = 0; i < SIZE; i++)
cin >> test[i];
swap(test, SIZE);
//USE LOOP TO DISPLAY ELEMENT ONE BY ONE
for(int i = 0; i < SIZE; i++)
cout << test[i] << endl;
return 0;
}

how to save the sorted arrays in textfile?

I have a program that sorted arrays how can i save in text file?
for example: the sorted arrays is: 1, 2, 3, 4, 5.
how can i save in text file named. Sorted elements".
I've tried many ways but the sorted array wouldn't save in text file.
I am a newbie so I find it difficult.
here is my code.
#include <iostream>
using namespace std;
int main() {
cout << "Enter number of element:";
int n; cin >> n;
int a[n];
for(int i=0;i<n;i++)
{
cout << "element number " << (i+1) << " : ";
cin >> a[i];
}
int e=1, d=3;
int i, j, k, m, digit, row, col;
int length = sizeof(a)/sizeof(int);
int bmat[length][10];
int c[10];
for(m=1;m<=d;m++)
{
for(i=0;i<10;i++)
{
c[i]=-1;
}
for(i=0;i<length;i++)
{
digit=(a[i]/e)%10;
c[digit]++;
row=c[digit];
col=digit;
bmat[row][col]=a[i];
}
k=-1;
for(i=0;i<10;i++)
{
if(c[i]!=-1)
{
for(j=0;j<=c[i];j++)
{
k++;
a[k]=bmat[j][i];
}
}
}
e=e*10;
}
cout << endl;
cout << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
cout << a[i] << " , ";
}
cout << endl;
system("pause");
return 0;
}
//Use this code
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
int main()
{
int n = 0;
cout << "Enter number of element:";
cin >> n;
//Data Structure
std::vector<int> list;
//push back element in vector
for(register int i=0;i<n;++i)
list.push_back(rand()%10 + 1);
//do shuffling before sorting because rand() generates increasing order number
std::random_shuffle(list.begin(),list.end());
std::sort(list.begin(),list.end());
ofstream textfile;
textfile.open ("E:\\example.txt");
for(size_t i= 0;i<list.size();++i)
textfile << list[i] <<" ";
textfile.close();
}
If you can write the sorted array to std::cout, then you can write it to a file. In C++, the console is the same as a file.
Put this at the end of main:
cout << "Sorted array:" << endl;
print_array( std::cout, a, n ); // Show the results to the user.
std::ofstream save( "array.txt" ); // Open a new file (or overwrite).
print_array( save, a, n ); // Save the results for later.
system("pause");
return 0;
}
and put the printing code in a new function, which may be defined before main:
void print_array( std::ostream & s, int * a, int n ) {
for(int i=0;i<n;i++)
{
s << a[i] << " , ";
}
s << endl;
}
#include<iostream>
#include<fstream>
using namespace std;
int compare(int, int);
void sort(int[], const int);
int compare(int x, int y){
return(x > y);
}
void swap(int *x, int *y){
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void display(int array[], int n){
for (int i = 0; i<n; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void writeToFile(int array[], int n){
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
}
void sort(int table[], const int n) {
for (int i = 0; i < n; i++){
for (int j = 0; j < n - 1; j++) {
if (compare(table[j], table[j + 1]))
swap(&table[j], &table[j + 1]);
}
}
}
int main(){
int quantity;
int* tab;
ofstream outfile;
cout << "Enter number of element: ";
cin >> quantity;
tab = new int[quantity];
cout << "Element:\n\n" << endl;
for (int i = 0; i < quantity; i++){
int x = i;
cout << "#" << ++x << ":";
cin >> tab[i];
}
sort(tab, quantity);
cout << "The Sorted Elements are: ";
display(tab, quantity);
writeToFile(tab, quantity);
cout << endl;
getchar();
getchar();
//system("pause");
return 0;
}
in short, add this block to your code:
ofstream myfile;
myfile.open("example.txt");
for (int i = 0; i<n; i++) {
myfile << array[i];
if (i != n - 1){
myfile << ", ";
}
}
myfile.close();
You can use C++ fstream class, since you want to output, you can use ofstream here. You should just replace some "cout" with ofstream instance:
At the beginning of the code state it:
ofstream ofs("./sorted_elem.txt", ofstream::out);
When want to output:
ofs << "Sorted array:" << endl;
for(int i=0;i<n;i++)
{
ofs << a[i] << " , ";
}
ofs << endl;
In C++ you really want to use std::vector or some other nice container for storing arrays of numbers. For writing an array to file you need to open the file and individually write each element to the file (all untested).
#include <fstream>
int main()
{
std::ofstream fp("output.txt");
int data[5]; // todo: fill
for (unsitned i = 0; i < 5; ++i)
{
fp << data[i] << ' ';
}
}
And to read again:
#include <fstream>
int main()
{
std::ifstream fp("output.txt");
// todo: Determine the size of the array or guess it (don't guess it!)
unsigned array_size = 5;
int data[array_size];
int n = 0;
while (fp.good() && n < array_size) fp >> data[n++];
}
But because we are using C++, we can use std::vector:
#include <fstream>
#include <vector>
int main()
{
std::vector<int> me(5); // todo: fill
std::ofstream fp("output.txt");
for (size_t i = 0; i < me.size(); ++i) fp << me[i] << ' ';
// C++11: for (int d : me) fp << d << ' ';
}
And,
#include <fstream>
#include <vector>
int main()
{
std::ifstream fp("output.txt");
std::vector<int> data;
double buf;
while (fp >> buf) data.push_back(buf); // no longer need to guess
}
I think, the copy option was not demonstrated here so far.
Please check this code. (Assuming your vector is ready to use, I've skipped it).
The example uses a C-array and a vector. Please use the later in your code whenever possible. But however, for copy-function both work:
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <fstream>
int main () {
int a[10]={0,1,2,3,4,5,6,7,8,9};
std::vector<int> v; for (int i=0; i<10; ++i)v.push_back(i*10); //0, 10, 20,...
std::ofstream fs_a( "c:/temp/out_a.txt" );
//store space separated
std::copy ( a, a+sizeof(a)/sizeof(a[0]), std::ostream_iterator<int>( fs_a, " ") );
//store coma-separated, as one-liner
std::copy ( v.begin(), v.end() ), std::ostream_iterator<int>( std::ofstream( "c:/temp/out_v.txt" ), ",") );
return 0;
}

Reading Text File of Floats into a 2D Vector in C++

I have a data file comprised of thousands of float values and I want to read them into a 2D vector array and pass that vector to another routine once it's stored the floats from the file. When I run this code it prints out;
[0][0] = 0, [0][1] = 0, etc.
The data file contains values like;
0.000579, 27.560021, etc.
int rows = 1000;
int cols = 2;
vector<vector<float>> dataVec(rows,vector<float>(cols));
ifstream in;
in.open("Data.txt");
for(int i = 0; i < rows; i++){
for(int j = 0; j < 2; j++){
in >> dataVec[i][j];
cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl;
}
}
in.close();
It looks to me like the file could not be opened. You did not test for success, so it will plough on regardless. All your values were initialized to zero and will stay that way because every read fails. This is conjecture, I admit, but I'd put money on it. =)
Try this solution, it works according to your specs:
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main(void)
{
ifstream infile;
char cNum[10] ;
int rows = 1;
int cols = 2;
vector<vector<float > > dataVec(rows,vector<float>(cols));
infile.open ("test2.txt", ifstream::in);
if (infile.is_open())
{
while (infile.good())
{
for(int i = 0; i < rows; i++)
{
for(int j = 0; j < 2; j++)
{
infile.getline(cNum, 256, ',');
dataVec[i][j]= atof(cNum) ;
cout <<dataVec[i][j]<<" , ";
}
}
}
infile.close();
}
else
{
cout << "Error opening file";
}
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
void write(int m, int n)
{
ofstream ofs("data.txt");
if (!ofs) {
cerr << "write error" << endl;
return;
}
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
ofs << i+j << " ";
}
void read(int m, int n)
{
ifstream ifs("data.txt");
if (!ifs) {
cerr << "read error" << endl;
return;
}
vector<float> v;
float a;
while (ifs >> a) v.push_back(a);
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++)
cout << "[" << i << "][" << j << "] = "
<< v[i*n+j] << ", ";
}
int main()
{
write(2,2);
read(2,2);
return 0;
}