c++中的字符串和整型

Strings and Ints in C++

本文关键字:整型 字符串 c++      更新时间:2023-10-16

首先,这是一个家庭作业,所以我希望得到帮助和指导,而不仅仅是代码的答案。

代码的目的应该是让用户输入一个数字和一个宽度。

如果宽度大于数字,则打印出的数字将在数字前面加零。例如,43 3会得到043

如果宽度不长,则打印数字:433 2将是433

我想我必须得到数字中的字符计数,并将其与宽度中的字符计数(if-else语句)进行比较。

然后,如果数字中的字符数较多,则输出该数字。否则,打印出宽度

我想我通过用宽度的长度减去数字的长度来得到0的个数。然后用它来设置0的个数。就像我说的,这是家庭作业,我宁愿自己学习,也不愿得到答案。

如果有人能帮忙,我将不胜感激。

    #include <iostream>;
    #include <string>;
    using namespace std;
    string format(int number, int width) {

    int count = 0;
      if (number > width)// This if-else is incomplete
          return ;  
      else              
    }
    int main() 
    {
     cout << "Enter a number: ";
     string n;
     cin >> n;
     cout << "Enter the number's width: ";
     string w;
     cin >> w;
     format(n, w);
    }

不需要检查字符串或其他东西编写这些代码c++将自动为您完成。

#include <conio.h>
#include <iostream>
using std::cout;
using std::cin;
#include <string>;
using std::string;
#include <iomanip>
using std::setw;
void format(int number, int width)
{
    cout.fill('0');
    cout << setw(width) << number;
}
int main()
{
    cout << "Enter a number: ";
    int n;
    cin >> n;
    cout << "Enter the number's width: ";
    int w;
    cin >> w;
    format(n, w);
    _getch();
    return 0;
}