我可以将字符串转换为int,以便在C ++的头文件中实现计算吗? [英] Can I convert a string to an int in order to implement calculations in header files for C++?

查看:68
本文介绍了我可以将字符串转换为int,以便在C ++的头文件中实现计算吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我有一个项目,包括返回日期值,这是一个字符串,/将月份与日期和年份分开。



因此,当日期由用户输入和/或在构造函数中声明时,它将采用MMDDYYYY格式。



IE

日期:12212000



我需要以12/21/2000格式退回



如何在头文件中实现它?我搜索和尝试过的每种语法都不起作用。所以我假设我无法计算字符串...我怎样才能转换为int?或者还有其他方法可以不计算吗?



我尝试过:



这是我的代码看起来像...



无法人口统计信息:: printDateOfBirth()

{

cout<< (dateOfBirth / 1000000)<< setprecision(2)<<固定<< /

<< ((dateOfBirth / 10000) - (100 *(dateOfBirth / 1000000)))

<< setprecision(2)<<固定<< /<< (dateOfBirth%10000)

<< setprecision(2)<<固定<< endl;

}

解决方案

由于输入日期是一个字符串,您只需将其拆分为三个子组件子串,然后用'/'字符连接这些子串。不需要转换。


通常代码在cpp文件中实现。在头文件中实现称为内联编程,它在优化和调试中会产生一些问题。以下是一些解释,包括赞成和反对。



要阅读这些值,您可以使用 sscanf 功能。



日历计算本身就是一门艺术。 :-O

Ok, so I have a project that consists of returning the date value, which is a string, with "/" separating the month from day and day from year.

So when the date is either inputted by the user and/or declared in constructor, it'll be in the format MMDDYYYY.

I.E.
date: 12212000

I need to return it in this format "12/21/2000"

How can I implement that in the header file? Every syntax I've searched and tried doesn't work. So I'm assuming I cannot calculate string... how can I convert to int? Or is there another way to do this without calculation?

What I have tried:

this is what my code looks like...

void DemographicInformation::printDateOfBirth( )
{
cout << (dateOfBirth/1000000) << setprecision(2) << fixed << "/"
<< ((dateOfBirth/10000)-(100*(dateOfBirth/1000000)))
<< setprecision(2) << fixed << "/" << (dateOfBirth%10000)
<< setprecision(2) << fixed << endl;
}

解决方案

Since the input date is a string, you just need to split it into its three component substrings, and then concatenate those substrings with the '/' characters. No conversion is necessary.


Normally code is implemented in a cpp-file. Implementing in the headers is called inline programming and it makes some problems in optimization and debugging. Here is some explanation with pro and cons.

For reading the values you could use the sscanf function.

And calendar computation is an art of itself. :-O


这篇关于我可以将字符串转换为int,以便在C ++的头文件中实现计算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆