Making structured (even) spaces in C++ for displaying data - c++

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

Related

Two Consecutive for loop in C++, Second loop is not working

Objective: I have two arrays. 1st Array is: evenList and the 2nd is: oddList. I want to print the even and odd numbers between the given ranges in this format.
This is my code,
cout << "\nEven numbers between " << lowerLimit << " to " << upperLimit << ": ";
for(int i; i < evenList.size(); i++){
cout << evenList[i] << " ";
}
cout << "\n\nOdd numbers between " << lowerLimit << " to " << upperLimit << ": ";
for(int j; j < oddList.size(); j++){
cout << oddList[j] << " ";
}
the first for loop prints the desired output but the second loop don't show the odd numbers. Here is the output:
I've read some of contents about for loops already but I just can't get the answer. If someone facing the same question or problem and got the answer, please share. I will really appreciate it.
You're not initializing your iterators. int i; should be int i = 0;, and likewise for int j. As it is now, this is undefined behavior. It's just chance that it worked the first time and not the second time, it might as well work both times, not work at all, crash right off the bat or do something entirely different.
Does your compiler emit a warning for this code? Ideally, it should say something like "uninitialized local variable 'i' used". Always listen to compiler warnings, they can help point out some common mistakes. If your compiler issues no warning here, try to see if you can configure it to be more strict with warnings.
I have two point that is leading you to your undesired output.
It is always good to initialize a variable. In most cases, it might lead you to segmentation fault. In the above code, you've not initialized the variables in the for loop.
I have not used C++ but I suppose that you're using array, evenList and oddList. And you're using a condition j<oddList.size(). The only way this condition can go wrong is if doesn't have any element in oddList array. Check whether you have any elements in those array.
Try to use FOR EACH LOOP to prevent the variable initialization confusion.
for(string s : eventList){ cout << s << endl; }
and same for the second loop. Hope this time it works
You can also use а Range-based for loop
cout<<"\nEven numbers between " << lowerLimit << " to " << upperLimit << ": ";
for (const auto &e: evenList)
{
cout << e << " ";
}
cout << "\n\nOdd numbers between " << lowerLimit << " to " << upperLimit << ": ";
for (const auto &o: oddList)
{
cout << o << " ";
}

Why arrays do not print whole table?

#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.

segmentation fault with single integer

So I'm making a class which is just an easy way to manipulate an array of a different class and perform a few operations on it (fractions if you wanted to know)
NOTE: this is my homework but I don't think this violates any kind of rule because I'm not asking how to do it, but what the issue is. However, if you would have any sort of moral dilemma with this, I'm just letting you know now.
The function uses a for loop to go through an array - but not out of array bounds, because I changed the code to not even use the array
for (int i = first - 1; i < last - 1; i++) cout << i;
and I still get a seg fault when i is 4.
In the scope of the function call, i is not a variable.
The line of output from this call is
0123
Segmentation fault
so for all I know, changing i to 4 causes the error.
Member data in the class is
private:
int size;
Fraction arr[20];
the function in the header is
Fraction Product(int first, int last) const;
and the code that uses it preceding the error is this (from Bob Myers FSU CS Dept)
http://www.cs.fsu.edu/~myers/cop3330/hw/hw4files/main.cpp
#include <iostream>
#include "flist.h"
using namespace std;
int main()
{
int start;
Fraction entry;
FList a;
cout << "Welcome!\n";
cout << a;
cout << "How many numbers to start with (1 - 20)? ";
cin >> start;
cout << "Please input the " << start << " starting fractions\n";
for (int i = 0; i < start; i++)
{
cout << "Fraction #" << (i+1) << ": ";
entry.Input();
a.Insert(entry);
}
cout << "\nHere's the list:\n" << a;
cout << "Size of list = " << a.Size() << '\n';
cout << "Sum of items in list = " << a.Sum();
cout << "\nProduct of first 5 fractions in list = " << a.Product(1,5);
I don't know much about computer organization and what's really going on behind memory allocation but I don't see how an integer can change value without changing the amount of bytes used and then become invalid memory, so I would really appreciate someone who can say I'm approaching this the wrong way.

Sudoku game design problems C++

I have (yet another) question about chars. Thanks to those who helped me with this before. I'm trying to do mainly 4 things at this point in the program. That is:
Build a 2D array 9x9 and fill it with underscores.
Ask for a row/column and then the number that the user wishes to go into that row/column as many times as the user wants.
Replace the specified blanks with the specified numbers.
Output the entire 9x9 char array on an ASCII art Sudoku board.
(Solving will come later.)
My problem is that when I enter the row/column and the number that I want to go into that row/column the dash that was originally in that spot disappears, but the number I entered does not appear in its place.
Here is the code so far:
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main () {
//Builds 9x9 char array.
char dash[9][9];
for (int array=0; array<9; array++) {
for (int array2=0; array2<9; array2++) {
dash[array][array2]='_';
}
}
cout << "Input the row #, then the column #, then the number that you wish to fill that spot." << endl;
cout << "Remember that a Sudoku board is 9x9." << endl;
cout << "When you wish to finish input and solve, type all 0's and press enter." << endl;
int rowb;
char row[99];
int columnb;
char column[99];
int numb;
char num[99];
//Inputs the row/column and number to go into specified row/column.
int control=0;
while (rowb!=0){
control++;
cout << "Row: ";
cin >> rowb;
cout << "Column: ";
cin >> columnb;
cout << "Number: ";
cin >> numb;
row[control]=rowb-1;
column[control]=columnb-1;
num[control]=numb;
}
int length;
length=strlen(row);
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control];
}
//Builds the Sudoko board and outputs the full 9x9 array.
cout << "╔═══════════╦═══════════╦═══════════╗" << endl;
for (int count=0; count<3; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=3; count<6; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╠═══════════╬═══════════╬═══════════╣" << endl;
for (int count=6; count<9; count++) {
for (int count2=0; count2<3; count2++) {
cout << "║_" << dash[count][count2*3] << "_|_" << dash[count][count2*3+1] << "_|_" << dash[count][count2*3+2] << "_";
}
cout << "║" << endl;
}
cout << "╚═══════════╩═══════════╩═══════════╝" << endl;
return 0;
}
There is a problem assignment of the number entered in the loop.
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control]; //<<<--- Assignment issue.
}
You are assigning an integer value in a character array & thus when you display you will get the corresponding char for the ascii value & not the integer. Try changing the assignment as follows:
//Replaces the _'s in the specified rows/columns and replaces them with the integer the user specified. This is where I think I'm having the problem.
for (control=0; control<length; control++) {
dash[row[control]][column[control]]=num[control] + '0'; // Convert to ascii value of the integer, but will fail if not b/w 0 & 9.
}
Checking if the number entered in is between 1 & 9 is also advised if you choose to use the above observation.
Please add checks for the row & column entered as enter values which are not b/w 1 & 9 will lead to undefined behaviour due to accessing out of bound array elements if the values entered are not b/w 1 & 9.
Also as mentioned by Benjamin Lindley please update strlen code.
Hope this helps!
length=strlen(row);
This is undefined behavior, because row[0] was never initialized, and you never null terminate the string.
char row[99];
...
int control=0;
while (rowb!=0){
control++;
...
row[control]=rowb-1;
...
Notice that the first time through the loop, control is 1. So, you're setting the value of row[1], but not row[0]. Move the increment to the end of the loop. There may be some other problems, but this is the primary one responsible for the behavior you're seeing.
Also, for strlen to work, you need to null terminate the string.
And finally, you're making the same mistake you've made in this question and this question. Why aren't you seeming to get that? Chars display differently than ints. The following code will not display the number 1:
char c = 1;
std::cout << c;
Look at the answers to those other two questions.

Formatting columns in C++

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 " ".