将字符串转换为整数部分 C++ [关闭]

Posted

技术标签:

【中文标题】将字符串转换为整数部分 C++ [关闭]【英文标题】:Converting a string into sections of integers C++ [closed] 【发布时间】:2016-04-22 22:51:21 【问题描述】:

嗨,所以我有一个时间,即 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;

【问题讨论】:

我建议您将您的程序减少到尽可能少的工作,以显示您正在尝试做什么,而不添加任何不必要的代码。 建议?我会坚持 【参考方案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

【讨论】:

这还不错,但具有破坏性。可怜的TimeString 再也不会一样了。 @user4581301 : Beeing 能够制作完美的副本是数字技术的标志之一 :) 是的,但需要知道他们必须这样做。一刀切,一个令人讨厌的冲击。【参考方案2】:

您可以将整数作为流读取,然后读取分隔符。 ':' 字符停止读取数字。

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

【讨论】:

以上是关于将字符串转换为整数部分 C++ [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

将 C++ 字符串操作转换为 C 的问题 [关闭]

如何将一个字符串转换为三个整数

将字符串元素转换为整数C++ [重复]

将矩阵字符串数组转换为整数矩阵? C++

替代 itoa() 将整数转换为字符串 C++? [复制]

如何将 C++ 或 C 中的字符串转换为整数数组?