[英]C++ - Concatenating strings (like PHP?)
我環顧四周,但找不到一個好的答案。
我有這樣的文件: text1.txt text2.txt text3.txt
用戶想要指定要打開的文件:
int x;
string filename;
cout << "What data file do you want to open? (enter an int between 1 -> 3): ";
cin >> x;
filename = "P3Data" << x << ".txt" ; //does not compile
myfile.open(filename);
正確的方法是什么?
要使用流接口,您需要一個stringstream
:
std::ostringstream filename;
filename << "P3Data" << x << ".txt";
myfile.open( filename.str().c_str() );
否則,您可以使用+連接兩個strings
。
在C ++ 11中,您可以這樣說:
#include <string>
const std::string filename = std::string("P3Data") + std::to_string(x) + std::string(".txt");
如果沒有C ++ 11,則可以使用boost::lexical_cast
或字符串流或snprintf
。 另外,您也可以從std::cin
讀入字符串而不是整數。
(如果讀取為整數,請使用條件檢查將讀取括起來以驗證操作: if (!(std::cin >> x)) { /* error! */ }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.