编写一个函数来取一个整数并返回一个包含格式化版本的std :: sting [英] Write a function to take an integer and return a std::sting containing a formatted version
问题描述
你好窥视。
我只想拿一个整数并返回一个字符串,其格式包括逗号。
我不关心语言环境,我只想要它包含逗号。
我正在使用C ++ 11并且代码将运行在其他。我需要用Google搜索并试用我找到的无数解决方案,但有些不起作用(特别是那些带有语言环境),有些甚至没有编译,其他只是使用标准输出而不是字符串。
它应该是简单的,当然?
(我是新的为了C ++ BTW所以要温柔!)
并且请尝试解雇你有什么尝试告诉我们你的代码等评论 - 这里有点意思我向你展示一页又一页不起作用的代码。
我会对一些只是循环字符串的东西感到满意,将一个额外的逗号连接到坦率地说,每三个字符输出一个字符串 - 即便如此当我尝试它时引起异常 - 但这可能是因为我不知道如何正确地迭代std :: string!
Hello peeps.
I just want to take an integer and return a string with the formatting to include commas.
I don't care about locale, I just want it to include commas.
I am using C++ 11 and the code will run on an iDevice.
I have googled and tried umpteen solutions I found, but some don't work (specifically those with locales) and some don't even compile, others just use std output rather than strings.
It should be simples, surely?
(I am new to C++ BTW so be gentle !)
And please try to lay off the "what have you tried" "show us your code" etc. comments - there's little point me showing you page after page of code that doesn't work.
I'd be happy with something that just loops through a string, concatenating an extra comma into and output string every three characters, frankly - even that seemed to cause an exception when I tried it - but that's probably because I don't know how to iterate over a std::string properly!
推荐答案
从迭代开始字符串:这很简单! std :: string有一个operator []重载,所以你可以逐个访问每个字符:
Start by iterating over the string: that's easy! std::string has an operator[] overload, so you can access each character one-by-one:
std::string myStr = "Hello!";
for(unsigned int i = 0; i < myStr.length(); i++)
{
char c = myStr[i]; //this is your character
cout << c;
}
所以...在每三个字符后添加一个逗号?实际上并不复杂:
So...adding a comma after each three characters? Not complex, really:
int commaAt = 3;
std::string myStr = "Hello there!";
for(unsigned int i = 0; i < myStr.length(); i++)
{
if (commaAt == 0)
{
cout << ',';
commaAt = 3;
}
char c = myStr[i]; //this is your character
cout << c;
commaAt--;
}
如果我想要返回一个字符串而不是cout-ing怎么能我这样做了吗?
你做的几乎就是你所展示的,但是试图将这些字符连接到另一个我开始异常的字符串......
当你想到你在做什么时,这也很容易:
"if i wanted to return a string rather than cout-ing how can i do that?
It was doing pretty much what you show, but trying to concat the chars to another string where I started to get exceptions..."
That's also pretty easy, when you think about what you are doing:
int commaAt = 3;
std::string myStr = "Hello there!";
std::string output = "";
for(unsigned int i = 0; i < myStr.length(); i++)
{
if (commaAt == 0)
{
output += ',';
commaAt = 3;
}
commaAt--;
char c = myStr[i]; //this is your character
output += c;
}
这篇关于编写一个函数来取一个整数并返回一个包含格式化版本的std :: sting的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!