将字符串转换为整数C ++的部分

时间:2016-04-22 22:51:21

标签: c++ string int

嗨所以我给了时间,即05:10:12并将其存储到一个字符串中,但我需要帮助将小时部分(05)转换为int然后将分数部分(10)转换为int然后秒部分(12)进入一个int所以我可以预先形成其他方程式。请帮忙。

#include <iostream>
#include <cmath>
#include <cctype>
#include <string>
#include <iomanip>
#include <fstream>
using namespace std;

const int max = 50; //max transactions possible                                                                     

void get(string&, string&, ifstream&);
void format(string&);
void average();
void deviation();
void median();
void print(string, ofstream&, string, string);

int main()
{
  ifstream inf;
  ofstream outf;
  string filename, name, stime, etime;
  int hour, min, sec, totalsec;
  double average, sd, median;

  cout << "Please enter name of input file:" << endl;
  cin >> filename;

  inf.open(filename.c_str());
  outf.open("kigerprog05out");

  outf << "Morgan Kiger LecSec1002 LabSec1005 Assignment 05" << endl << endl;
  outf << "NAME" << right << setw(20) << "START TIME" << setw(15) << "END TIME" << setw(15) << "TOTAL SECS" << endl;

  inf >> name;

  while(inf)
    {
      get(stime, etime, inf);
      format(name);
      print(name, outf, stime, etime);

      inf >> name;
    }
  inf.close();
  outf.close();

  return 0;
}

void get(string& stime, string& etime, ifstream& inf)
{
  inf >> stime;
  inf >> etime;

  return;
}

void format(string& name)
{
  int wlen = name.length();
  name[0] = toupper(name[0]);
  for(int i=1; i<wlen; i++)
    {
      name[i] = tolower(name[i]);
    }

  return;

}

void print(string name, ofstream& outf, string stime, string etime)
{
  outf << left << name << right << setw(18) << stime << setw(15) << etime << setw(15) << endl;

  return;
}

2 个答案:

答案 0 :(得分:1)

如果我理解正确,您需要以HH:MM:SS格式从字符串中提取整数时间吗?

std::string TimeString = { "05:10:12" };                       //Sample string

std::replace( TimeString.begin(), TimeString.end(), ':', ' '); //Replace ':' with whitespace
int Hours, Minutes, Seconds;
std::istringstream ss(TimeString);
ss >> Hours >> Minutes >> Seconds;                             //Extract time from stringstream

答案 1 :(得分:0)

您可以将整数读取为流然后读取分隔符 &#39;:&#39;字符会停止读取数字。

unsigned int hours;
unsigned int minutes;
unsigned int seconds;
char separator;
//...
inf >> hours;
inf >> separator; // read the ':'.
inf >> minutes;
inf >> separator; // read the ':'.
inf >> seconds;

您可以将流从fstream更改为istringstream