[英]Printing the contents of a file using the #include directive (preprocessor)
[英]Preprocessor directive to create file names
我必須逐個打開文件才能用C / C ++閱讀。 文件的名稱是in0,in1,in2,in3 .....我試圖使用預處理器指令來創建文件名。 我想要類似的東西。
for(int i=0;i<n;i++)
{
string inp_file="/path/"+"in"+APPEND(i); //to generate /path/in1 etc
open(inp_file);
}
其中APPEND是MACRO。 以來
#define APP(i) i
可以生成價值
#define APP(i) #i
可以將令牌轉換為字符串。
我試圖在很多方面將它們結合起來但卻失敗了。 如何獲得所需的結果,或者甚至可以用宏獲得這樣的結果?
在您的情況下,變量i
不是編譯時常量,因此不可能使用預處理器或模板特化,因為在編譯時根本不知道該值。 你可以做的是將整數轉換為字符串 - boost.lexical_cast
是最容易使用的解決方案之一:
for (int i = 0; i < n; ++i) {
// Generate /path/in1 etc
std::string inp_file = "/path/in"+ boost::lexical_cast<std::string>(i);
open(inp_file);
}
如果你碰巧有一個支持C ++ 11的編譯器,你可以使用std::to_string()
。 例如:
for (int i = 0; i < n; ++i) {
// Generate /path/in1 etc
std::string inp_file = "/path/in" + std::to_string(i);
open(inp_file);
}
希望能幫助到你。 祝好運!
Vlad回答的附錄 - 如果由於某種原因你不能/不願意使用Boost,你可以使用帶有stringstream
類的標准C ++來完成你想要的任務:
#include <sstream>
void Foo() {
for (int i = 0; i < n; ++i) {
std::stringstream converter;
converter << "/path/in" << i;
open(converter.str());
}
}
如果你沒有使用boost,試試這個:
namespace StringUtils
{
// Converts any type which implements << to string (basic types are alright!)
template<typename T>
std::string StringUtils::toString(const T &t)
{
std::ostringstream oss;
oss << t;
return oss.str();
}
}
用這種方式:
for(int i=0;i<n;i++)
{
string inp_file="/path/"+"in"+ StringUtils::toString(i); //to generate /path/in1 etc
open(inp_file);
}
只是對現有答案的補充,如果你使用的是較新的編譯器和標准庫,c ++ 11引入了std::to_string()
。 所以你可以寫這樣的代碼:
for(int i = 0; i < n; i++) {
string inp_file = "/path/in"+ std::to_string(i);
open(inp_file);
}
C解決方案是這樣的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n =4;
char nstr[12];
sprintf(nstr, "%d", n);
int nlen = strlen( nstr );
const char *fd = "/path/in";
char buff[ strlen(fd) + nlen + 1 ];
sprintf( buff, "%s%d", fd, n );
/* for testing */
printf( "%s\n", buff );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.