注册 登录
编程论坛 C++教室

string里放数字

未未来 发布于 2013-05-08 00:29, 557 次点击
一道C++的题目

写一函数,输入一个四位数字,要求输出这四个数字字符,但每两个数字间空格。如输入1990,应输出"1 9 9 0"。
我的代码
程序代码:
#include<iostream>
#include<string>
using namespace std;
void p(string &x){
for(size_t i=0;i<x.size();++i){

cout<<x[i]<<" ";

}
}
int main(){
    string st;
    cin>>st;
p(st);
    return 0;
}



我直接把数字放string ,我想问这也合理吗。。或者更合理的是使用什么
1 回复
#2
rjsp2013-05-08 08:45
不知道,但C++正宗的做法如下:
程序代码:
#include <iostream>
#include <string>
#include <locale>
using namespace std;

struct thousands_sep_facet:public std::numpunct<char>
{
    explicit thousands_sep_facet( size_t r=0 ) : std::numpunct<char>(r)
    {
    }
    char do_thousands_sep() const
    {
        return ' ';
    }
    string do_grouping() const
    {
        return "\001";
    }
};

int main( void )
{
    cout << 1990 << endl;

    locale loc = std::cout.imbue( locale(locale(), new thousands_sep_facet) );
    cout << 1990 << endl;
    std::cout.imbue( loc );

    cout << 1990 << endl;

    return 0;
}

以上代码只是给你了解一下C++。出题者肯定不是希望你用标准的做法来解决这个问题。
1