2013-12-08 78 views
0

如何将连字符打印到ex,344-34-4333这样的输出中。如果从具有不带连字符的数字的文件中读取此ID,我如何才能打印xxx-xx-xxxx 3到2到4?打印连字符/破折号?

+2

这就是:'std :: cout <<“ - ”;' – 2013-12-08 22:01:38

+0

把334344333变成344-34-4333:http://www.cplusplus.com/reference/string/string/insert/ – nhgrif

回答

1

std::string类有很多构造函数来帮助你解决这些问题。成员函数substr()也很有用。

一个快速和肮脏的例子:

std::string x("344344333"); 
std::string res = x.substr(0, 3) + '-' + s.substr(3, 2) + '-' + x.substr(5,4); 

对于更复杂的字符串,你可能更愿意使用std::ostringstream类。

+0

如果我有一个文件中的ID号码列表,并且我从文件中读取数据(包含为344344333),我想打印344-34-4333。在文件中循环时,我需要如何做到这一点。我尝试使用模数等,但似乎无法得到它。 – user3078999

+0

@ user3078999:当你处理字符时,不需要做复杂的数学运算,只需要字符串和偏移量。像'std :: ifstream f('data.txt'); std :: string x; while(std :: getline(f,x)){/ *转换并在答案中写入x * /}'。 – rodrigo