繁体   English   中英

C ++中的字符串和整数

[英]Strings and Ints in C++

首先,这是用于家庭作业,因此,我希望获得帮助和指导,而不仅仅是代码中的答案。

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

如果宽度大于数字,则将数字打印出来,并在数字前加上零。 例如, 43 3将给出043

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

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

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

我想我是通过从宽度的长度中减去数字的长度来获得零的数量的。 然后使用它来设置零的数量。 就像我说的那样,这是家庭作业,宁愿学习而不是得到答案。

如果有人可以提供帮助,我们将不胜感激。

    #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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM