所以我试图将前面的 0
强制转换为 int
以便稍后对其进行处理。现在,我在 SO 或任何其他网站上看到的所有教程都使用与此类似的内容:
cout << setfill('0') << setw(2) << x ;
虽然这很棒,但我似乎只能让它与 cout
一起工作,但是,我不想输出我的文本,我只想填充数字以供以后使用。
到目前为止,这是我的代码..
#include <iostream>
#include <string>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include <sstream>
/*
using std::string;
using std::cout;
using std::setprecision;
using std::fixed;
using std::scientific;
using std::cin;
using std::vector;
*/
using namespace std;
void split(const string &str, vector<string> &splits, size_t length = 1)
{
size_t pos = 0;
splits.clear(); // assure vector is empty
while(pos < str.length()) // while not at the end
{
splits.push_back(str.substr(pos, length)); // append the substring
pos += length; // and goto next block
}
}
int main()
{
int int_hour;
vector<string> vec_hour;
vector<int> vec_temp;
cout << "Enter Hour: ";
cin >> int_hour;
stringstream str_hour;
str_hour << int_hour;
cout << "Hour Digits:" << endl;
split(str_hour.str(), vec_hour, 1);
for(int i = 0; i < vec_hour.size(); i++)
{
int_hour = atoi(vec_hour[i].c_str());
printf( "%02i", int_hour);
cout << "\n";
}
return 0;
}
想法是输入一个 int
,然后将其转换为 stringstream
以拆分为单个字符,然后返回一个整数。但是,任何小于数字 10 (<10) 的东西,我都需要在左边补上一个 0。
谢谢大家
编辑: 您在上面看到的代码只是我主要代码的一个片段,这是我正在努力工作的部分。
很多人都无法理解我的意思。所以,这是我的想法。好的,所以该项目的整个想法是接受用户输入(时间(小时、分钟)日(数字、月号)等)。现在,我需要将这些数字分解成相应的 vector (vec_minute、vec_hour 等),然后使用这些 vector 指定文件名。就像: cout << vec_hour[0] << ".png"; cout << vec_hour[1] << ".png";
现在,我知道我可以使用 for 循环来处理 vector 的输出,我只需要帮助将输入分解为单个字符。由于我要求用户将所有数字输入为 2 位数字,因此数字 10 以下的任何数字(数字前面带有 0)都不会拆分为数字,因为程序会在数字传递给拆分方法之前自动删除其前面的 0(即。你输入 10,你的输出将是 10,你输入 0\n9,你的输出将是一个数字 9)。我不能有这个,我需要在传递给拆分方法之前用 0 填充小于 10 的任何数字,因此它将返回 2 个拆分数字。我将整数转换为字符串流,因为这是我发现的拆分数据类型的最佳方式(如果您想知道的话)。
希望我能更好地解释一切:/
最佳答案
如果我对你的问题的理解正确,你可以将这些操纵器与 stringstream
一起使用,例如:
std::stringstream str_hour;
str_hour << setfill('0') << setw(2) << int_hour;
字符串流是输出流,因此 I/O 操纵器影响它们的方式与它们影响 std::cout
的行为的方式相同。
一个完整的例子:
#include <sstream>
#include <iostream>
#include <iomanip>
int main()
{
std::stringstream ss;
ss << std::setfill('0') << std::setw(2) << 10; // Prints 10
ss << " - ";
ss << std::setfill('0') << std::setw(2) << 5; // Prints 05
std::cout << ss.str();
}
以及对应的live example .
关于c++ - 如何将前面的 0 强制为 int(而不实际输出它),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175688/