所以我試圖強制前面的0
到int
,以便稍後可以處理。現在,所有我已經看到了這樣的教程,或任何其他網站,都用類似於這樣:如何強制前面的0到一個int(實際上沒有輸出它)
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。
謝謝你們
編輯: 您在上面看到的代碼僅僅是我主要的代碼片段,這是位IM試圖使工作。
很多人都很難理解我的意思。所以,這是我的想法。好的,所以項目的整個想法是採取用戶輸入(時間(小時,分鐘)日(數字,月份數量等))。現在,我需要將這些數字分解爲相應的向量(vec_minute,vec_hour等),然後使用向量來指定文件名..如此: cout < < vec_hour [0] < <「.png」; cout < < vec_hour [1] < <「.png」;
現在,我知道我可以使用for循環來處理向量的輸出,我只需要幫助將輸入分解爲單個字符。由於我要求用戶輸入所有數字作爲2位數字,任何在數字10之下的數字(0之前的數字)都不會被分割爲數字,因爲程序在數字傳遞給分割方法之前自動刪除其前面的0。你輸入10,你的輸出將是10,你輸入0 \ n9,你的輸出將是一個單一的數字9)。我不能擁有這個,我需要填充任何小於10的數字,然後將其傳遞給split方法,因此它會返回2個分隔數字。我將整數轉換爲串流,因爲這是分割我發現的數據類型的最佳方式(無論您想知道)。
希望我解釋了一切好多了:/
字符串流的工作方式與輸出流相同。 – chris
如果你正在討論用前導零填充「int」本身,恐怕這沒有意義。整數不表示爲十進制數字的序列。 –
這怎麼沒有意義?在分析到split方法之前,我需要在單個數字int的左前方添加一個0。 0在int被加入到字符串中之前或之後添加是否無關緊要,我只需要在它傳遞之前在某個點處對其進行填充 – amartin94