2016-04-22 6 views
-3

こんにちは私は05:10:12の時間を与えられ、それを文字列に格納していますが、時間部分(05)をintに変換して分部分(10)私は他の方程式をプリフォームすることができるようにintに秒部分(12)をintに変換します。助けてください。文字列を整数のセクションに変換するC++

#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; 
} 
+0

不要なコードを追加することなく、あなたがしようとしていることを示す最小限の労力でプログラムを減らすことをお勧めします。 – mah

+0

提案しますか?私はそれに_insist_します。 –

答えて

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 
+0

それは悪くないですが、破壊的です。貧弱な 'TimeString'は再び決して同じではありません。 – user4581301

+0

@ user4581301:完璧なコピーを作成できるBeeingは、デジタルテクノロジーの特徴の1つです。 – Unimportant

+0

はい、しかし、これを行う必要があることを知る必要があります。カットアンドペストイドは厄介なショックのためにある。 – user4581301

0

整数をストリームとして読み取り、セパレータを読み取ることができます。
':'文字は数値の読み取りを停止します。

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にストリームを変更することができます。

関連する問題