C++/corrections in translation C# to C++
Expert: Zlatko - 1/23/2010
QuestionI have translation by Instant C++(C#edition)Tangible Software from C# to C++ as follows:
for (I = 1; I <= N; I++)
{
for (J = 1; J <= N; J++)
{
std::cout << " " + Strings::Format(A[I][J], "####0.0000");
}
std::cout << std::endl;
std::cout << std::endl;
}
But compilator C++ Express 2008 shows errors:Console has not been declared and Strings has not been declared. How to correct this array A outputs ?
AnswerHello Adam,
I am not so good with formatting output to the screen. In C++, output formatting is done by setting flags and other parameters in cout, and by putting stream manipulators into the cout line. See
http://www.arachnoid.com/cpptutor/student3.html for more of a tutorial.
In C++ and C#, arrays start at 0, and array indicies go from 0 to size-1
Below is your code with some values assigned to the array A and some formatting.
#include <iostream> // you need this for cout
#include <iomanip> // for setw
// with this you dont have to put std:: in front of cout
using namespace std;
int main(void)
{
const int N = 5;
float A[N][N];
std::cout.setf(std::ios_base::fixed);
std::cout.precision(4);
for (int I = 0; I < N; I++)
{
for (int J = 0; J < N; J++)
{
A[I][J] = (float)I + (float)J/10;
std::cout << " " << std::setw(8) << A[I][J];
}
std::cout << std::endl;
std::cout << std::endl;
}
return 0;
}