简体   繁体   English

C ++中的字符串和整数

[英]Strings and Ints in C++

First off, this is for a homework assignment, so I'd appreciate help and guidance rather than just the answer in code. 首先,这是用于家庭作业,因此,我希望获得帮助和指导,而不仅仅是代码中的答案。

The purpose of the code should be for a user to input a number and a width. 代码的目的应该是让用户输入数字和宽度。

If the width is longer than the number, the number will be printed out with zeros in front of the number. 如果宽度大于数字,则将数字打印出来,并在数字前加上零。 For example 43 3 would give 043 . 例如, 43 3将给出043

If the width isn't longer just the number would be printed: 433 2 would be 433 . 如果宽度不再长,则会打印数字: 433 2将是433

I think I have to get the count of characters in the number and compare it to the count of characters in the width ( if-else statement). 我想我必须获取数字中的字符数,并将其与宽度中的字符数进行比较( if-else语句)。

Then, if the number of characters in the number is more, print out the number. 然后,如果数字中的字符数更多,请打印出该数字。 Else, print out the width. 否则,打印出宽度。

I think I get the number of zeros by subtracting the length of the number from the length of the width. 我想我是通过从宽度的长度中减去数字的长度来获得零的数量的。 Then use that to set the number of zeros. 然后使用它来设置零的数量。 Like I said this is homework and would rather learn than be given the answer. 就像我说的那样,这是家庭作业,宁愿学习而不是得到答案。

If anyone can help, it'll be appreciated. 如果有人可以提供帮助,我们将不胜感激。

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

    }

no need to checking string or other things write these code C++ will do it for you automatically. 无需检查字符串或其他东西来编写这些代码,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