我的代碼用ifstream讀取一個文件並解析它,現在我改變了一些東西,而且我不需要讀取該文件,原因是從另一個地方讀取的,所以我有一個char * ifstream ...我怎麼能改變我的代碼,我使用ifstream.get()? 再次感謝C++ ifstream to char *
回答
您只需將您的char *
放入std::stringstream
即可。
std::stringstream buffer(your_string);
然後可以使用buffer
幾乎就像是一個std::ifstream
(您不能打開或關閉)。理想情況下,你的解析法將採取的std::istream
作爲參數的引用,那麼就不會介意什麼樣的輸入流接收:
void parse(std::istream & input);
因爲從std::istream
都std::ifstream
和std::stringstream
繼承,你可以通過它們作爲參數,並且您的解析器無需修改即可運行。
#include <sstream>
#include <fstream>
#include <iostream>
using namespace std;
void mung(istream & is) {
char c;
while(is >> c) {
cout << c << endl;
}
}
int main(int argc, char *argv[]) {
if (argc > 1) {
ifstream ifs(argv[1]);
mung(ifs);
}
else {
istringstream iss("here is some text to mung");
mung(iss);
}
}
正如其他人所說,你可以使用std::istringstream
,但在這種情況下, 我寧願不推薦使用的(但總是存在)std::istrstream
。或者乾脆 創建一個簡單的memory_streambuf
,與imemorystream
和 的omemorystream
:如果你不需要是雙向的,也不支持 尋求的memory_streambuf
是代碼不到10行,總是 有用的,並且留下了很多其他解決方案的複雜性。 (如果你只是在做這一次,當然,使用現有的解決方案 是首選,但我發現memory_streambuf
在 是有用的一些案件。)
作爲利益的問題,爲什麼偏好istrstream? – 2011-05-11 08:09:20
@unaperson簡單。也許習慣,在某種程度上,但是如果他有'char []'(由'char *'指向),那麼'istrstream'可以直接使用它; 'istringstream'將需要轉換爲'string'。沒什麼大不了的,如果'istrstream'不可用,我會使用'istringstream',但既然是這樣,爲什麼不使用可以完全滿足你需要的流。 (對於輸出,差異更加顯着,因爲當輸出太多字符時,ostrstream將停止並聲明錯誤。) – 2011-05-11 08:40:43
- 1. Char to Operator C++
- 2. C++ LPCTSTR to char *
- 3. vb.net byte [] to C++ char *
- 4. C++:無法從'std :: ifstream'轉換爲'char *'
- 5. 閱讀ifstream word for char *
- 6. char * string to hex arrary in C
- 7. Casting void * to char * in C
- 8. Casting to unsigned char in C
- 9. Python to C/C++ const char問題
- 10. C++ ifstream I/O?
- 11. C++ ifstream類錯誤
- 12. Cast char to short
- 13. char to string error
- 14. reinterpret_cast double to char *
- 15. char [] to uint64_t
- 16. Const Char to LPTSTR
- 17. String.Replace char to string
- 18. CString to char *
- 19. KeyEventArgs.Key to char
- 20. const char * to LPTSTR
- 21. memcpy CString to char *
- 22. fstream to const char *
- 23. Cast void * to char *
- 24. ifstream二進制讀/寫只需要char *?
- 25. GNU Guile SCM to char *
- 26. ifstream - > ofstream C++
- 27. Marshal StringBuilder to char * in C++/CLI(for IN/OUT)
- 28. TCHAR * to char * C++中的轉換
- 29. ifstream C++的問題
- 30. C++:ifstream作爲參數
爲什麼'stringstream',和不是'istringstream'?爲什麼他似乎並不需要額外的複雜性? – 2011-05-11 07:55:21
@詹姆斯:好點。我認爲,即使「ostringstream」或「istringstream」就足夠了,總是使用'stringstream'是我的一個壞習慣。 – 2011-05-11 07:56:59
謝謝牛仔!工作正常,我沒有改變太多我的代碼! – ghiboz 2011-05-11 08:21:29