Why don't people initialize i globally? - c++

So, it seems like 'i' is pretty much the universal counter in C++. It seems like in every for loop, people re-initialize 'i'. I have to ask, why don't they just initialize 'i' globally? 'i' would still have to be re-defined in each loop, so I don't see why there would be any confusion.
It just seems like this:
#include <iostream>
int i=0;
int main()
{
for (i=0;i<3;i++)
{
std::cout << i << "\n";
}
for (i=0;i<5;i++)
{
std::cout << "hello" << "\n";
}
return 0;
}
is easier to read, and faster to write than:
#include <iostream>
int main()
{
for (int i=0;i<3;i++)
{
std::cout << i << "\n";
}
for (int i=0;i<5;i++)
{
std::cout << "hello" << "\n";
}
return 0;
}

Excellent idea!
Here's a program that prints "hellohello" five times:
int i;
void print_twice(const std::string& s)
{
for (i = 0; i < 2; i++)
{
std::cout << s;
}
std::cout << std::endl;
}
int main()
{
for (i = 0; i < 5; i++)
{
print_twice("hello");
}
}
Or... does it? (Ominous organ music plays. The crows caw. Sirens in the distance.)

Related

Why only the first element of the array is initialized to -1? while rest of them are 0 [duplicate]

This question already has answers here:
Initialization of all elements of an array to one default value in C++?
(12 answers)
Closed 4 years ago.
I've initialized arr to -1 when I print them every element is initialized to 0 except the first element.
This is the small code of a bigger problem. I'm just struck here
#include <bits/stdc++.h>
using namespace std;
int fibo()
{
int static arr[100] = {-1};
for (int i = 0; i < 100; ++i)
{
cout << "arr[" << i <<"] : " << arr[i] << endl;
}
return -2;
}
int main(void)
{
cout << "Result : " << fibo() << endl;
return 0;
}
Simplest solution -- use std::vector<int>, and the initialization of all elements becomes available to you in a very easy form (I know there are template tricks that can be done, but IMO there is no need for that level of complexity for this in your code).
Example:
#include <vector>
#include <iostream>
int fibo()
{
static std::vector<int> arr(100,-1);
for (int i = 0; i < 100; ++i)
{
std::cout << "arr[" << i <<"] : " << arr[i] << "\n";
}
return -2;
}
int main(void)
{
std::cout << "Result : " << fibo() << "\n";
return 0;
}
Live Example
#include <bits/stdc++.h>
using namespace std;
int fibo()
{
int static arr[100];
for (int i = 0; i < 100; ++i)
{
arr[i] = -1;
}
for (int i = 0; i < 100; ++i)
{
cout << "arr[" << i <<"] : " << arr[i] << endl;
}
return -2;
}
int main(void)
{
cout << "Result : " << fibo() << endl;
return 0;
}
Try using this code

how do I get sequence of 'false' in an array

I am the beginner of C++, and any help will be very appreciated.
here is the code i can run successfully:
#include <Eigen/Dense>
#include <iostream>
using namespace Eigen;
main(){
bool findIn=false;
RowVectorXd A(10);
A<<false,true,false,true,true,false,false,false,true,true;
std::cout << A << std::endl;
for (int i=0;i<A.size();i++){
if(A(i)==findIn){
std::cout << i << std::endl;
}
}
system("pause");
}
the result is {0,2,5,6,7}, and I want to design a function, the code is as follows:
int seq(bool findIn, VectorXd &resdX){
VectorXd A;
for(int i=0;i<resdX.size();i++){
if(resdX(i)==findIn){
A =A+i;
}
}
return(A);
}
I want this function to return result like that {0,2,5,6,7}.But I don`t know how to set up a array to save the result or is there a function just like 'which' in R software to produce sequence above.
Sounds like you want a vector of integers:
#include <vector>
std::vector<int> seq(bool findIn, VectorXd &resdX)
{
std::vector<int> v;
for(int i=0;i<resdX.size();i++) {
if (resdX(i) == findIn) {
v.push_back(i);
}
}
return v;
}
You can then print its contents by iterating through it:
std::vector<int> result = seq(false, A);
for (int i : result) std::cout << i << '\n';
I did not understand what are you looking for.
If you want just to print a sequence of integers indexing findIn values you might code:
void seq(bool findIn, VectorXd &resdX) { // not int
std::cout << "{ ";
for(int i=0;i<resdX.size();i++) // go inside the array
if(resdX(i)==findIn) // if you find that resdX(i) value equals findIn value
std::cout << i << " "; // print i index
std::cout << "}" << std::endl; // at the end prints a new line
}
EDIT1:
Try to adapt the following snippet:
#include <list>
...
std::list<int> seq(bool findIn, VectorXd& resdX) {
std::list<int> l;
for(int i=0; i<resdX.size(); i++) {
if (resdX(i) == findIn) {
l.push_back(i);
}
}
return l;
}
void print_seq(std::list<int> list_) {
std::cout << "{ ";
std::list<int>::iterator it = list_.begin();
for (; it != list_.end(); ++it) {
std::cout << i << " ";
}
std::cout << " }\n";
}

Looping through array inside of stuct

I'm a student, learning pointers for the first time. My assignment doesn't allow the use of string classes and should be using pointer notation to access all elements within an array (no []).
Why am I not able to access an array inside of a struct via pointers? Is my syntax off?
#include <iostream>
using namespace std;
struct person
{
int favNums[4];
};
// Notation works here
void strCopy(char *from, char *to, int len)
{
for (int i = 0; i < len; i++)
{
*(to + i) = *(from + i);
}
}
// But doesn't work here
void sayNumsPointerNotation(person peep)
{
for (int i = 0; i < 4; i++)
{
//cout << peep.*(favNums + i) << endl;
}
}
// Would like to accomplish this.
void sayNums(person peep)
{
for (int i = 0; i < 4; i++)
{
cout << peep.favNums[i] << endl;
}
}
int main()
{
// Array outside of struct
char from[5] = "Word";
char to[5];
strCopy(from, to, 5);
cout << to << endl << endl;
// Array inside of struct non-pointer
person peep;
peep.favNums[0] = 0;
peep.favNums[1] = 1;
peep.favNums[2] = 2;
peep.favNums[3] = 3;
sayNums(peep);
cout << endl;
sayNumsPointerNotation(peep);
cout << endl;
}
This should work, hopefully you understand what was wrong.
#include <iostream>
using namespace std;
struct person
{
int favNums[4];
};
// Notation works here
void strCopy(char *from, char *to, int len)
{
for (int i = 0; i < len; i++)
{
*(to + i) = *(from + i);
}
}
// But doesn't work here (now it works)
void sayNumsPointerNotation(person* peep)
{
for (int i = 0; i < 4; i++)
{
cout << *(peep->favNums + i) << endl;
}
}
// Would like to accomplish this.
void sayNums(person peep)
{
for (int i = 0; i < 4; i++)
{
cout << peep.favNums[i] << endl;
}
}
int main()
{
// Array outside of struct
char from[5] = "Word";
char to[5];
strCopy(from, to, 5);
cout << to << endl << endl;
// Array inside of struct non-pointer
person peep;
peep.favNums[0] = 0;
peep.favNums[1] = 1;
peep.favNums[2] = 2;
peep.favNums[3] = 3;
sayNums(peep);
cout << endl;
sayNumsPointerNotation(&peep);
cout << endl;
}
Instead of
cout << peep.*(favNums + i) << endl;
Try this:
cout << *(peep.favNums + i) << endl;
Use
cout << *(peep.favNums + i) << endl;
.*, on the other hand, is a "member pointer", and means something different.

formatted output: columns

I am desperately trying to produce formatted output by using fstream: columns.
There are two functions (whatever functions Func1, Func2) which produce output (write to the same file, "example.dat"):
#include <fstream>
int main()
{
std::ofstream fout;
fout.open("example.dat");
for (int i=0; i<10; i++)
{
fout << Func1(i) << std::endl;
};
// Func2 depends on Func1, thus them **cannot** be written at the same time:
// fout << Func1() << " " << Func2() << std::endl;
for (int i=0; i<10; i++)
{
fout << Func2(i) << std::endl;
};
return 0;
}
The output will similar to:
Func1(0)
Func1(1)
.
.
.
Func1(9)
Func2(0)
Func2(1)
.
.
.
Func2(9)
My question is: How to produce this output as two columns:
Func1(0) Func2(0)
Func1(1) Func2(1)
.
.
.
While them are not simultaneously written.
I suspect that I need to use seekp(), tellp(), but unfortunately I am not a big expert in this.
Please help!
Thank you in advance.
vector<ostringstream> streams(10);
for (int i=0; i < 10; ++i)
{
streams[i] << Func1(i);
}
for (int i=0; i < 10; ++i)
{
streams[i] << " " << Func2(i);
}
ofstream fout("example.dat");
for (int i=0; i < 10; ++i)
{
fout << streams[i].str() << endl;
}
Why would you need seekp and tellp (and writing to the middle of a file is full of pitfalls for the unwary in any case)
Use a std::vector (syntax is probably wrong), thus:
std::vector<std::string> res1;
std::vector<std::string> res2;
res1.reserve(10);
res2.reserve(10);
for (std::size_t i = 0; i < 10; ++i)
{
std::stringstream s;
s << func1(i);
res1[i] = s.str();
}
//same for res2, func2
for (std::size_t i = 0; i < 10; ++i)
{
cout << res1[i] << " " << res2[i] << "\n";
}
That's probably the wrong formatting and bits will need tuning. And std::list might work better.
Assuming you really cannot keep them in memory, you could write to two files, seek back to the start, read them back in line by line and output to your final file to create your concatenated columns.
Something like this might work (I've not tested it):
#include <fstream>
#include <string>
int main()
{
std::fstream fs_func1;
std::fstream fs_func2;
std::ofstream fout;
fs_func1.open("func1.dat")
for (int i=0;i<10;i++)
{
fs_func1 << Func1(i) << std::endl;
}
fs_func1.seekg(0); // Set get pointer to start of file
fs_func2.open("func2.dat");
for (int i=0;i<10;i++)
{
fs_func2 << Func2(i) << std::endl;
};
fs_func2.seekg(0); // Set get pointer to start of file
fout.open("example.dat");
while (!fs_func1.eof() && !fs_func2.eof())
{
std::string func1_line;
std::string func2_line;
std::getline(fs_func1, func1_line);
std::getline(fs_func2, func2_line);
fout << func1_line << " " << func2_line << std::endl;
}
return 0;
}
There is probably a Unix command line tool that would do this for you in one step.
Untested, but the idea is to treat your file as a grid.
const int COLUMN_COUNT = 2;
const int COLUMN_WIDTH = 8;
const int ROW_WIDTH = COLUMN_COUNT * COLUMN_WIDTH + 1; // + 1 is for endl
void write_cell(std::ostream& out, int row, int column, double value) {
// how many rows is there in the file ?
out.seekp(0, std::ios_base::end);
int row_count = out.tellp() / ROW_WIDTH;
// Do we need to create more rows ?
for(int i = row_count; i <= row; i++) {
out.seekp(ROW_WIDTH - 1, std::ios_base::cur);
out << endl;
}
// compute cell position
int pos = row * ROW_WIDTH + column * COLUMN_WIDTH;
// move to cell position
out.seekp(pos);
// write the cell content
out << std::setw(COLUMN_WIDTH) << value;
}
int main()
{
std::ofstream fout;
fout.open("example.dat");
for (int i=0; i<10; i++)
{
write_cell(fout, i, 0, Func1(i));
};
for (int i=0; i<10; i++)
{
write_cell(fout, i, 1, Func2(i));
};
return 0;
}
for (int i=0;i<10;i++)
{
fout << Func1(i);
};
fout<<endl;
for (int i=0;i<10;i++)
{
fout << Func2(i);
};
fout<<endl;

How do you convert an int into a string in c++

I want to convert an int to a string so can cout it. This code is not working as expected:
for (int i = 1; i<1000000, i++;)
{
cout << "testing: " + i;
}
You should do this in the following way -
for (int i = 1; i<1000000, i++;)
{
cout << "testing: "<<i<<endl;
}
The << operator will take care of printing the values appropriately.
If you still want to know how to convert an integer to string, then the following is the way to do it using the stringstream -
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
int number = 123;
stringstream ss;
ss << number;
cout << ss.str() << endl;
return 0;
}
Use std::stringstream as:
for (int i = 1; i<1000000, i++;)
{
std::stringstream ss("testing: ");
ss << i;
std::string s = ss.str();
//do whatever you want to do with s
std::cout << s << std::endl; //prints it to output stream
}
But if you just want to print it to output stream, then you don't even need that. You can simply do this:
for (int i = 1; i<1000000, i++;)
{
std::cout << "testing : " << i;
}
Do this instead:
for (int i = 1; i<1000000, i++;)
{
std::cout << "testing: " << i << std::endl;
}
The implementation of << operator will do the necessary conversion before printing it out. Use "endl", so each statement will print a separate line.