I have the following program that generates a multiplication table. A formatting problem arises when the outputs reach the double digits. How do I straighten out the columns?
#include <iostream>
using namespace std ;
int main()
{
while (1 != 2)
{
int column, row, c, r, co, ro;
cout << endl ;
cout << "Enter the number of columns: " ;
cin >> column ;
cout << endl ;
cout << "Enter the number of rows: " ;
cin >> row ;
cout << endl ;
int temp[column] ;
c = 1 ;
r = 1 ;
for(ro = 1; ro < row ; ro ++ ){
for(co = 1; co < column ; co ++ ){
c = c ++ ;
r = r ++ ;
temp [c]= co * ro;
cout << temp[c] << " ";
}
cout << endl ;
}
system("pause");
}
}
C++ had setw and setfill for just this purpose. setw sets the width and setfill sets the fill character.
In your case, you can just use something like:
#include <iostream>
#include <iomanip>
int main (void) {
std::cout << std::setw(5) << 7 << std::endl; // will output " 7".
return 0;
}
You have a number of other problems with that code, at least some of which are listed below:
You don't allocate enough space for your array, it should be column*row (or use a two-dimensional array).
Array indexes start at 0, not 1.
c = c++ is not a good idea, c++ will be enough to increment c.
You may be trying to increment c twice in each iteration, once if the for statement itself and once in the for body.
system("pause"); is an ugly hack where the language provides a perfectly good getchar or cin equivalent.
while (1 != 2) just looks plain wrong :-) since 1 will never equal 2. Just use while (1) or for(;;) - any coder worth their salt will know what you mean.
use the setw output manipulator:
cout << setw(3) << temp[c];
By default, this uses spaces to fill, which it looks like you want.
You will need to include iomanip as the documentation says.
You can set width of your column elements by using stream manipulators like this:
cout << setw(3) << temp[c]
But this is something you need to fix besides: c = c++; does not increment the variable!
This is one of those situations where the old-fashioned printf is a lot easier than cout. Replace cout << temp[c] << " " with printf("%2d ", temp[c]).
And I hope you've discovered the bug in your c calculation.
You could use "\t" instead of " ".
Related
I've created a program that displays multiplication table:
for (int a=1; a<=10; a++)
{
cout << endl;
for (int b=1; b<=10; b++)
{
cout << " [" << a*b <<"] ";
}
}
The problem is it displays it like this:
I've tried to use setw() but it doesn't work since it sets it to all the numbers so it just makes the result spaced out a little bit more. Anything else i can try?
If you look at the documentation for setw you will note that you need to stream it to your stream like so:
cout << " [" << setw(3) << a*b <<"] ";
Here is a live example.
If you need to calculate the size that you need for the stream width, you can look up a question like this:
Efficient way to determine number of digits in an integer
#include <iostream>
using namespace std;
int main()
{
double donation[10];
int index = 0;
cout.setf(ios::fixed);
cout << "Enter sum of money for donating: ";
while (index < 10 && cin >> donation[index])
{
cout << "donation #" << 1 + index++ << ": " << donation[index] << endl;
}
return 0;
}
Result
That code couldn't display right value of donation...
I could check the mistake is '1 + index++', but I don't know why did.
Why my code using '1 + index++' has a difference with code when I use 'index++' in the next line.
Keep to the idiomatic way instead of trying to understand stranger constructions and also mixing increments with function/operator parameters should be avoided (see sequence points):
for (int index = 0; index < 10; ++index)
{
if (! std::cin >> donation[index])
break;
std::cout << "donation #" << (1 + index) << ": " << donation[index] << std::endl;
}
This should do what is expected and should be understood with some knowledge of C++. It runs at most 10 times, tries to fill input to the array and displays when the input works or stops when the input fails. The only issue would be better validation of the user input.
I'm struggling getting my columns to align on an assignment I have for school. The directions are to ensure that each column heading aligns correctly with its respective column. I've tried everything I've found online so far, including the cout.width() and the setw(), neither of which has worked. I'm hoping it's not due to me implementing these methods incorrectly, though I can't think of any other reason why they wouldn't work. The assignment specifically has 2 student names to use as an example. Jones, Bob and Washington, George. Due to the major difference in the number of characters between one student and the next, the columns just won't align. I know that setting a column width should fix that, but in my case it isn't. Then code I'm supplying is using the setw() method, but I can supply how I tried using the cout.width() if needed. Any help is GREATLY appreciated.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
using std::cout;
using std::cin;
using namespace std;
const int ARRAYSIZE = 2;
struct studentData{
string lastName;
string firstName;
float studentGpa;
}studentArray[ARRAYSIZE];
void displayData(int a);
int main()
{
int counter = 0;
for (int a = 0; a < ARRAYSIZE; a++)
{
cout << "Enter last name: " << endl;
cin >> studentArray[a].lastName;
cout << "Enter first name: " << endl;
cin >> studentArray[a].firstName;
cout << "Enter GPA: "<< endl;
cin >> studentArray[a].studentGpa;
counter++;
}
cout << "\n\n";
displayData(counter);
return 0;
}
void displayData(int a)
{
int newSize = a;
cout << left << setw(20) <<"\nName(Last, First)";
cout << right << setw(20) << "GPA\n";
for (int z = 0; z < newSize; z++)
{
cout << studentArray[z].lastName << ", " << studentArray[z].firstName;
cout << right << setw(20) << fixed << setprecision(2) <<studentArray[z].studentGpa << endl;
}
}
And my console input/output:
Enter last name:
Jones
Enter first name:
Bob
Enter GPA:
3.0
Enter last name:
Washington
Enter first name:
George
Enter GPA:
4.0
Name(Last, First) GPA
Jones, Bob 3.00
Washington, George 4.00
You are along the right lines, but std::setw only applies to the next output operation. If you turn printing the name into one operation, instead of 3 (last, comma, first) then you can pad the width of that more easily:
void displayData(std::size_t a)
{
std::cout << std::left
<< std::setw(20)
<< "Name(Last, First)"
<< "GPA\n";
for (std::size_t z = 0; z < a; ++z)
{
std::cout << std::left
<< std::setw(20)
<< (studentArray[z].lastName + ", " + studentArray[z].firstName)
<< std::fixed << std::setprecision(2)
<< studentArray[z].studentGpa
<< '\n';
}
}
Output:
Name(Last, First) GPA
Jones, Bob 3.00
Washington, George 4.00
Here, both for printing the column headings, and for the student names, I use std::left to say that the content should be at the left of the padded total, and std::setw to pad this output operation to 20 characters total (by default it will pad with spaces).
In both cases, this is the 1st column in the output, so I don't need to do anything with the 2nd column. If you had a 3rd column, you would need to pad the 2nd as well.
I also replaced your ints with size_ts for array indexing. It's a little point, but you shouldn't really use a signed type for indexing into a container where accessing a negative index would be Undefined Behaviour.
Also, please reconsider your use of what are often considered bad practices: using namespace std; and endl (those are links to explanations).
My teacher gave me this and I got an error when adding
«setprecision(3) <<setiosflags(ios::fixed) »
Could you tell me why?
#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;
main()
{
float x1,y1,x2,y2,x3,y3,x4,y4,PQ,QR,RS,SP,Keliling;
cout << "Masukkan koordinat empat titik berbeda (x,y) :\n";
cout<< "P(x,y):" ;
cin >> x1>>y1 ;
cout <<"\n" ;
cout << "Q(x,y) :" ;
cin >> x2>>y2 ;
cout <<"\n" ;
cout << "R(x,y) :" ;
cin>> x3>>y3 ;
cout <<"\n" ;
cout << "S(x,y) :" ;
cin >>x4>>y4;
cout <<"\n" ;
PQ = sqrt(pow(x2-x1,2)+pow(y2-y1,2));
QR = sqrt(pow(x3-x2,2)+pow(y3-y2,2));
RS = sqrt(pow(x4-x3,2)+pow(y4-y3,2));
SP = sqrt(pow(x1-x4,2)+pow(y1-y4,2));
Keliling = PQ+QR+RS+SP;
cout << "Kelilingnya adalah " << Keliling <<" satuan";
«setprecision(3) <<setiosflags(ios::fixed) »
return 0 ;
}
Because you misunderstood the instruction. You can't just dump it onto its own line in code at the end of your program and expect it to magically work, and you can't keep the French quotation marks on it.
You need to think logically about what your program does, and in what order. What do you want to accomplish, and how can you tell the computer how to help you accomplish it?
A good start would be Googling setprecision to find out what it is and how to use it.
Furthermore, your program has other problems, such as the missing return type for main.
sestprecision is a manipulator that you can pass into cout stream to define how many digits after comma should be displayed so for example:
cout << setprecision(2) << 0.122312 << endl;
will result with
0.12
it causes error because you have not put it into stream but nowhere - it is not a statement!
The problem with the line is that it is not a valid cpp statement
the setprecision statement need to be connected to an output stream and since you are using the standard output. The correction will go like this
cout << setprecision(2) << fixed << endl;
Again just as preferencebean stated, your main function should include a return type.
int main()
{
//code;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int d,m;
int districts=3;
int months = 12;
double sales[districts][months];
for (d=0 ; d < districts; d++)
{
for(m=0; m< months; m++)
{
cout << "Enter sales for District " << d+1 << ":" << " and Month " << m+1 << ": ";
cin >> sales[districts][months];
}
}
cout << "\n\n\n";
cout << setw(40) << "Months\n";
cout << setw(26) << "1 2 3 4 5 6 7 8 9 10 11 12\n";
for (d=0; d < districts ; d++)
{
cout << "District " << d+1;
for(m=0; m< months; m++)
{
cout << ": " << sales[districts][months];
}
}
return 0;
}
This code after running takes only two input values from user and after that a window appear displaying message a problem caused the program to stop working correctly.
There are no compilation errors and I am unable to find the problem. Is there anyone who can help?
You use variables d and m as counter-variables for your loops, but inside the loops you use the maximum value for both of them (districts and months) instead of d and m.
Change this: cin >> sales[districts][months]; to this: cin >> sales[d][m];
Also, this: cout << ": " << sales[districts][months]; to this: cout << ": " << sales[d][m];.
The term sales[districts][months] refers to a particular element sales[3][12], which also happens to be out of bounds for the 2-d array.
The reading loop is repeatedly reading a value to sales[districts][months], i.e. to sales[3][12], which - since array indexing starts at zero in all dimensions, doesn't exist. That gives undefined behaviour.
The output loops are repeatedly outputting the same value, which also gives undefined behaviour.
A common symptom (but not the only possible one) of undefined behaviour is abnormal program termination - and you are seeing an example of that.
There is also the wrinkle that
int districts=3;
int months = 12;
double sales[districts][months];
involves a variable length array (VLA) which is a feature of C (from the 1999 C standard or later) but is not valid C++. If that construct works for you, your compiler supports a non-standard extension.