现在我需要输入到底有几个苹果,如果是只是显示,可以直接printf("I have %d apple.", x); 但是我希望在我输入苹果个数后把整句话放到一个string中,也就是 string y=“I have 6 apples.”;(假设我输入了6,变量y),请问如何做到?
2 回答
![?](http://img1.sycdn.imooc.com/54584d080001566902200220-100-100.jpg)
森栏
TA贡献1810条经验 获得超5个赞
如果只是想输入输出,那么很简单:
int dd;
cin >> dd;
cout << "I have " << dd << " apples." << endl;
如果想保存到string变量中,那么需要做一步整型转字符串操作,可以使用_itoa函数:
int dd;
string str = "I have ";
char c[11];
_itoa(dd, c, 10);
str += c;
str += " apples.";
cout << str << endl;
![?](http://img1.sycdn.imooc.com/545850c80001ebf202200220-100-100.jpg)
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
如下代码:
#include <sstream> #include <iostream> using namespace std; int main() { ostringstream ostr; int x = 1; ostr << "I have " << x << (x > 1 ? " apples" : " apple" ) << "." ; string str = ostr.str(); cout << str << endl; system ( "pause" ); return 0; } |
- 2 回答
- 0 关注
- 101 浏览
添加回答
举报
0/150
提交
取消