現在我需要輸入到底有幾個蘋果,如果是只是顯示,可以直接printf("I have %d apple.", x); 但是我希望在我輸入蘋果個數后把整句話放到一個string中,也就是 string y=“I have 6 apples.”;(假設我輸入了6,變量y),請問如何做到?
2 回答

森欄
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;

翻過高山走不出你
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 關注
- 120 瀏覽
添加回答
舉報
0/150
提交
取消