c++中的字符串和整型
Strings and Ints in C++
首先,这是一个家庭作业,所以我希望得到帮助和指导,而不仅仅是代码的答案。
代码的目的应该是让用户输入一个数字和一个宽度。
如果宽度大于数字,则打印出的数字将在数字前面加零。例如,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;
}
相关文章:
- C 字符串返回字符串的整数/双精度/长整型值
- 提升不良词法强制转换:将字符串转换为无符号长整型时,无法将源类型值解释为目标
- 将字符串中以十六进制形式存储的负长整型值转换为 C++ 中的长整型变量
- 如何以优雅高效的方式将无符号/有符号整数/长整型转换为 C 字符串?
- 如何在 c++ 中将十六进制字符串转换为长整型字符串
- 将字符串转换为长整型
- 将字符串存储在无符号长整型的向量中
- 整型到字符串:不使用stoi库
- 将十六进制二进制或十进制字符串转换为长整型字符串C++
- c++中的字符串和整型
- c++中字符串到整型的哈希函数
- 使用整型变量检查用户输入是整型还是字符串
- 将数字字符串转换为整型,然后再转换为数组
- 从文件中抓取值以查看它们是整型还是字符串
- 将字符串转换为整型数组
- 如何正确输入整型,整型的向量,整型和字符串的向量
- 将字符串映射到整型CPP -输出在执行期间挂起
- 真正长的整型字符串到整型的转换
- 如何将十六进制字符串转换为无符号长整型字符串
- 需要解析整型字符串并获得空白