Fix for my code

Hi, if my input is 3 3 3 *
output will be 3***3***3***3

However there should be an exception where if the user inputs n, the letter n would then be represented by numbers like such:
input:

3 3 n b

output:

0bbb1bbb2bbb3

the problem in my code is that instead of 0bbb1bbb2bbb3, the 3 is instead becomes the letter n (0bbb1bbb2bbbn) which is not the one im looking for.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int main(){
	
    char maj;
    char min;
    int a=0;
    int num;
    int width;
    cin >> num >> width >> maj >> min;
    for (int i = 0; i < num; i++){
        if(maj=='n'){
            cout<< i;
        }else{cout << maj;}
        for (int j = 0; j < width; j++){
            cout << min;
        }
    }
    if(maj!='n'){
        cout<<maj;
    }
    return 0;
    }
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
   char major, minor;
   int num, width;
   cin >> num >> width >> major >> minor;
   if ( major == 'n' )
   {
      cout << 0 << setfill( minor );
      for ( int i = 1; i <= num; i++ ) cout << setw( width + 1 ) << i;
   }
   else
   {
      cout << major << setfill( minor );
      for ( int i = 1; i <= num; i++ ) cout << setw( width + 1 ) << major;
   }
}


3 3 n b
0bbb1bbb2bbb3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <string>

int main() 
{
    char maj   {};
    char min   {};
    int  num   {};
    int  width {};

    std::cin >> num >> width >> maj >> min;

    std::string fill(width, min);

    for (int i{ 0 }; i <= num; i++)
    {
        if (maj == 'n') 
            std::cout << i;
        else 
            std::cout << maj;
        
        if (i < num) 
            std::cout << fill; 
    }
    
    return 0;
}
5 3 n ~
0~~~1~~~2~~~3~~~4~~~5
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <string>
using namespace std;

int main()
{
   char major, minor;
   int num, width;
   cin >> num >> width >> major >> minor;
   string line( num * (width+1) + 1, minor );
   for ( int i = 0; i <= num; i++ ) line[i*(width+1)] = ( major == 'n' ? '0' + i % 10 : major );
   cout << line << '\n';
}


5 3 n ^
0^^^1^^^2^^^3^^^4^^^5
@The Grey Wolf may i ask what does the fill do?
fill is a std::string, sequence of chars, in the example it is created and initialised with '~~~'. The reason I used it was to take the embedded for loop out of your code as it doesn't change each time around the outer loop.
Topic archived. No new replies allowed.