c++ why programs reads only first value - c++

program should read numbers from data.txt file and then print them, but prints only first value good, all other values are the same -9.25596e+061
const char CDfv[] = "Data.txt";
const int cmax = 1000;
//---------------------------------------------------------
void read_print_data (double A[], int& x);
//--------------------------------------------------------
int main()
{
ofstream fr;
double A[cmax];
int x;
ifstream fv ("Data.txt");
read_print_data(A,x);
system("Pause");
return 0;
}
void read_print_data (double A[], int& x)
{
ifstream fd(CDfv);
fd >> x;
for (int i = 0; i < x; i++)
{
fd >> A[i];
cout << i + 1 << " " << A[i] << endl;
fd.close();
}
}

You are closing the stream prematurely, You need to move
fd.close();
to be outside the loop.
So the code should look like
for (int i = 0; i < x; i++)
{
if (fd >> A[i]) {
cout << i + 1 << " " << A[i] << endl;
} else {
// Error has occurred
}
}
fd.close();

Related

C++ Console is blank when program is run

This might be a stupid question I'm still very new to coding. For my CS class I was given code for the basics of a boardgame. When I try to run the code it just comes up blank in my console, I tried to print "check" at the very beginning of main but still nothing prints to the console. No errors come up
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
using namespace std;
class square {
private:
int move;
string message;
char symbol;
public:
square();
void print();
int action();
void set(int, char, string);
};
void print_board(square[], int, int);
void read_board(square[]);
void check_position(int &);
const int board_length = 20;
int main() {
cout << "check";
int current_player = 1, roll;
int player1_position = 0, player2_position = 0;
square the_board[board_length];
srand(time(NULL));
read_board(the_board);
print_board(the_board, player1_position, 1);
print_board(the_board, player2_position, 2);
do {
cout << "\n\n\nPlayer " << current_player << " type enter to roll.\n";
cin.ignore();
roll = 1 + (rand() % 5);
cout << "Player " << current_player << " rolled a " << roll << ".\n";
if (current_player == 1) {
player1_position += roll;
check_position(player1_position);
player1_position += the_board[player1_position].action();
check_position(player1_position);
} else {
player2_position += roll;
check_position(player2_position);
player2_position += the_board[player2_position].action();
check_position(player2_position);
}
print_board(the_board, player1_position, 1);
print_board(the_board, player2_position, 2);
current_player = (current_player % 2) + 1;
} while ((player1_position < board_length-1) && (player2_position < board_length - 1));
current_player = (current_player % 2) + 1;
cout << "\nPlayer " << current_player << " Wins!!!\n";
cin.ignore();
return 0;
}
void read_board(square b[]) {
ifstream infile;
infile.open("game.txt");
int square_number, square_move;
string square_message;
char square_symbol;
while (!infile.eof()) {
infile >> square_number >> square_move >> square_symbol;
getline(infile, square_message);
if (square_number < board_length) {
b[square_number].set(square_move, square_symbol, square_message);
}
}
}
void print_board(square b[], int player_position, int player_number) {
for (int i=0; i < board_length; i++) {
if (i != player_position) {
b[i].print();
} else {
cout << player_number;
}
}
cout << "Goal\n";
for (int i=0; i < board_length; i++) {
cout << "-";
}
cout << "\n";
}
void check_position(int &p) {
if (p < 0) {
p = 0;
}
if (p >= board_length) {
p = board_length - 1;
}
}
square::square() {
symbol = ' ';
move = 0;
message = "";
}
int square::action() {
cout << message << endl;
return move;
}
void square::print() {
cout << symbol;
}
void square::set (int m, char s, string a_message) {
move = m;
symbol = s;
message = a_message;
}
Modify you read_board() to
void read_board(square b[]) {
ifstream infile;
infile.open("game.txt");
int square_number, square_move;
string square_message;
char square_symbol;
while (infile >> square_number >> square_move >> square_symbol) {
getline(infile, square_message);
if (square_number < board_length) {
b[square_number].set(square_move, square_symbol, quare_message);
}
}
}
Change cout<<"check"; to cout<<"check"<<endl;
Without the new line added, the out buffer is not flushed before your code gets hung in your read_board function

Method declaration issue

The program should read n resistances and a voltage from the keyboard and then calculate the equivalent resistance and the current.
My problem is that it calculates based only on the last entered resistance.
Is it possible to declare a method inside a function? or should I give up this completely unpractical approach
#include "stdafx.h"
#include<iostream>
#include<conio.h>
using namespace std;
class rez {
float r;
public:
void set(int n);
float val() { return r; }
};
void rez :: set(int n) { //n is the number of resistances
int i;
for (i = 1; i <= n; i++) {
cout << "R" << i << "=";
cin >> r;
}
}
float serie(rez r1,int n)
{
float s=0;
int i;
for (i = 1; i <= n; i++)
{
s = s+ r1.val();
}
return s;
}
float para(rez r1, int n)
{
float s = 0;
int i;
for (i = 1; i <= n; i++)
{
s = s + (1/r1.val());
}
return 1/s;
}
int main()
{
char c, k = 'y'; // 'c' selects series or para
rez r1;
int n;
cout << "number of resis:";
cin >> n;
cout << endl;
while (k != 'q')
{
r1.set(n);
float i, u;
cout << "\n Vdc= ";
cin >> u;
cout << endl;
cout << "series or para(s/p)?"<<endl;
cin >> c;
switch (c)
{
case('s'):cout <<"\n equiv resistance = "<< serie(r1,n)<<endl;
i = u / serie(r1, n);
cout << "curr i = " << i << " amp";
break;
case('p'):cout << "\n equiv res = " << para(r1, n)<<endl;
i = u / para(r1, n);
cout << "cur i = " << i << " amp";
break;
}
cout <<endl<< "\n another set?(y/q)?"<<endl;
cin >> k;
}
return 0;
}
It is because when you read in the resistances you are setting the value of the total resistance each time not adding to the total resistance.
void rez :: set(int n) { //n is the number of resistances
int i;
for (i = 1; i <= n; i++) {
cout << "R" << i << "=";
cin >> r; // <- this sets the value of r, it does not add to it
}
}
To fix this you should create a temporary variable to store the input resistance and then add it to the total resistance
void rez :: set(int n)
{
int i;
for (i = 1; i <= n; i++)
{
float input;
cout << "R" << i << "=";
cin >> input;
r += input;
}
}

read int per line c++ error needs solution

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)

I can't make the transition to a new line when writing results to a file

I guess that my problem is very trivial, but unfortunately (maybe because I'm really tired) I can't find a solution by myself. Well, my program generates results that I would like to write to successive lines of a text file, because I need to create a graph from them. Unfortunately, in my case, each result is saved in the same line by removing the previous result. Can you help me to improve this code? Thank you.
#include <iostream>
#include <cstring>
#include <ctime>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <fstream>
using namespace std;
int fp(int x, int y)
{
return (x<=y);
}
void sort_shell(int *tablica, int ilosc)
{
int licznik=0;
int h;
int i;
int temp;
int c=1;
fstream plik;
for (h=1; h<=ilosc/9; h=ilosc/pow(2,h));
c++;
for(; h>0; h /= 3)
{
for (i=h; i<ilosc; i++)
{
int j;
temp = tablica[i];
for (j = i-h ; j>=0; j -=h)
{
if (temp <=tablica[j])
{
tablica[j+h] = tablica[j];
licznik++;
}
else
break;
}
tablica[j+h] = temp;
}
}
/*cout << "\nPo sortowaniu Shellem." << endl;
for(i=0; i<ilosc; i++)
{
cout << tablica[i] << "\t";
}*/
plik.open( "shell.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
void sort_hibbard(int x[], int n)
{
int i, j,k, increment, temp,licznik=0;
long swp=0, comp=0;
int val;
fstream plik;
val=log(n+1)/log(2);
increment =pow(2,val)-1;
while (increment > 0)
{
for (i=0; i<increment; i++)
{
for(j=0; j<n; j+=increment)
{
temp=x[j];
for(k=j-increment; k>=0&&temp<x[k]; k-=increment)
{
comp++;
swp++;
x[k+increment]=x[k];
licznik++;
}
x[k+increment]=temp;
swp++;
licznik++;
}
}
comp++;
val--;
if(increment!=1)
increment=pow(2,val)-1;
else
increment = 0;
}
/*cout << "\nPo sortowaniu Hibbardem." << endl;
for(i=0; i<n; i++)
{
cout << x[i] << "\t";
}*/
plik.open( "hibbard.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
void sort_sedgewick(int *tablica, int ilosc)
{
int h = 0, i, g, t, j;
int c = 1;
int licznik = 0;
int temp;
fstream plik;
vector <int> tmp;
tmp.push_back(h);
do
{
h = (pow(4,c) + (3 * pow(2,c-1)) + 1); // funkcja z wikipedi O(N^4/3)
tmp.push_back(h);
if(h < ilosc) c++;
}while(h < ilosc);
for(g=ilosc/c;g>0;g/=c)
{
for(i=ilosc-g-1;i>=0;i--)
{
t = tablica[i];
for(j=i+g;(j<ilosc)&&!fp(t,tablica[j]);j+=g)
{
tablica[j-g] = tablica[j];
licznik++;
}
tablica[j-g] = t;
licznik++;
}
}
/*cout << "\nPo sortowaniu SEDGEWICKiem." << endl;
for(i=0;i<ilosc;i++)
{
cout << tablica[i] << "\t";
}*/
plik.open( "sedgewick.txt", std::ios::in | std::ios::out );
if(plik.good() == true)
{
plik << licznik << "\n";
plik.close();
}
//cout << "\nIlosc operacji :" << licznik << "\n";
}
int main()
{
int i, n;
//cout << "Podaj rozmiar tablicy (W tablicy znajda sie liczby od 1 do 100): ";
//cin >> n;
for(n=1000;n<=100000;n+=1000)
{
cout << n << "\n";
int zbior[n];
int prawy = 200;
srand(time(NULL));
//cout << "Przed sortowaniem." << endl;
for (int i = 0; i < n; i++)
{
if (i%2 == 0)
{
zbior[i] = rand()%prawy;
//cout << zbior[i] << "\t";
}
else
{
zbior[i] = rand()%prawy+200;
//cout << zbior[i] << "\t";
}
}
cout << endl;
sort_shell(zbior, n);
sort_hibbard(zbior, n);
sort_sedgewick(zbior, n);
}
return 0;
}
You need to use std::ios::app to append data to a file. You should also keep these files open for the duration of the reporting; you seem to be re-opening them for each iteration.

Sorting an array of 1000 integers

I'm having an issue sorting an array of 1000 integers with the following code. It worked fine with 10 integers but with 1000 it seems keep going I'm assuming it's some kind of memory leak.
I've never sorted before a small explanation of my errors would be helpful also.
Thank you
class RandomNumbers
{
private:
int intRandomNumbers;
public:
int getRandomNumbers();
void setRandomNumbers(int intPRandomNumbers);
RandomNumbers(void);
};
-----------------------------------------------------------
void printArray(const int intArray[], int intLength);
int searchFull(const int intArray[], int intLength, int intSearchItem);
void sortBubble(int intArray[], int intLength);
int searchLinear(const int intArray[], int intLength, int intSearchItem);
int searchBinary(const int intArray[], int intLength, int intSearchItem);
--------
//Getters and setters for RandomNumber class.
RandomNumbers::RandomNumbers()
{
setRandomNumbers(0);
}
void RandomNumbers::setRandomNumbers(int intPRandomNumbers)
{
intRandomNumbers = intPRandomNumbers;
}
int RandomNumbers::getRandomNumbers()
{
return intRandomNumbers;
}
void printArray(const int intArray[], int intLength) {
for(int intIndex = 0; intIndex < intLength - 1; intIndex++) {
cout << intArray[intIndex] << ", ";
}
cout << intArray[intLength - 1] << endl;
}
int searchFull(const int intArray[], int intLength, int intSearchItem) {
int intLocation = -1;
int intCounter = 1;
for(int intIndex = 0; intIndex < intLength; intIndex++) {
cerr << "searchFull: " << intCounter++ << endl;
if(intArray[intIndex] == intSearchItem)
{
intLocation = intIndex;
}
}
return intLocation;
}
void sortBubble(int intArray[], int intLength){
int intTemp = 0;
int intIteration = 0;
int intIndex = 0;
for(intIteration = 1; intIteration < intLength; intIteration++) {
for(intIndex = 0; intIndex < intLength - intIteration; intIndex++) {
if(intArray[intIndex] > intArray[intIndex + 1]) {
intTemp = intArray[intIndex];
intArray[intIndex] = intArray[intIndex + 1];
intArray[intIndex + 1] = intTemp;
}
printArray(intArray,intLength);
}
}
}
int searchLinear(const int intArray[], int intLength, int intSearchItem) {
int intLocation = -1;
int intCounter = 1;
for(int intIndex = 0; intIndex < intLength && intSearchItem >= intArray[intIndex]; intIndex++) intIndex++)
{
cerr << "searchLinear: " << intCounter++ << endl;
if(intArray[intIndex] == intSearchItem)
{
intLocation = intIndex;
}
}
return intLocation;
}
int searchBinary(const int intArray[], int intLength, int intSearchItem) {
int intFirstIndex = 0;
int intLastIndex = intLength - 1;
int intMiddle = 0;
bool boolFound = false;
while(intFirstIndex <= intLastIndex && !boolFound) {
intMiddle = (intFirstIndex + intLastIndex) / 2;
if(intArray[intMiddle] == intSearchItem) {
boolFound = true;
} else if(intArray[intMiddle] > intSearchItem) {
intLastIndex = intMiddle - 1;
} else {
intFirstIndex = intMiddle + 1;
}
cerr << "searchBinary: " << intFirstIndex << ", " << intMiddle << ", " << intLastIndex << endl;
}
if(boolFound) {
return intMiddle;
} else {
return -1;
}
}
int main() {
srand (time(NULL));
ofstream myfile;
myfile.open ("RandomNumber.txt");
if (myfile.is_open())
{
for (int i = 0; i < 1000; ++i)
{
int RandomNumbers = rand() % 1000 + 1;
myfile << RandomNumbers << "\n";
}
}
myfile.close();
int array_size = 1000;
int * array = new int[array_size];
int position = 0;
ifstream fin("RandomNumber.txt");
if(fin.is_open())
{
cout << "File opened!!! Loading array. ";
while(!fin.eof() && position < array_size)
{
fin >> array[position];
position++;
}
cout << "Displaying array..." << endl <<endl;
for(int intIndex = 0; intIndex < array_size; intIndex++)
{
cout << array[intIndex] << endl;
}
fin.close();
}
else
{
cout<< "File could not be opened." << endl;
}
cout << searchFull(array, array_size, 43) << endl;
cout << searchLinear(array, array_size, 43) << endl; //Incorrect not sorted
cout << searchFull(array, array_size, 5) << endl;
cout << searchLinear(array, array_size, 5) << endl; //Incorrect not sorted
sortBubble(array, array_size);
cout << searchFull(array, array_size, 43) << endl;
cout << searchLinear(array, array_size, 43) << endl;
cout << searchBinary(array, array_size, 43) << endl;
cout << searchFull(array, array_size, 5) << endl;
cout << searchLinear(array, array_size, 5) << endl;
cout << searchBinary(array, array_size, 5) << endl;
system("PAUSE");
return 0;
};
while(!fin.eof() is a blunder. What happens after the last value has been read, but before eof() occurs? (answer: You'll get the last entry copied twice). Fix it by going:
while ( position < array_size && fin >> array[position] )
position++;
Also, you should be displaying and sorting with position as the counter, not array_size.
Maybe your sortBubble function has a bug, or maybe it is just taking a long time to run. What happens if you try with 100 numbers? Can you post the code for it?