問題描述
我想將一些數據輸出到文件中.例如假設我有兩個雙精度向量:
I'd like to output some data to a file. For example assume I have two vectors of doubles:
vector<double> data1(10);
vector<double> data2(10);
是否有一種簡單的方法可以將其輸出到文件中,以便第一行包含標題data1"和data2",然后是實際內容.的功能輸出數據將傳遞各種不同的數組,因此對名稱進行硬編碼標題是不可能的 - 理想情況下我想轉換變量名稱到某個字符串,然后輸出該字符串,后跟向量數組的內容.但是,我不確定如何將變量名 'data1' 轉換為字符串,或者確實如果它可以輕松完成(從閱讀論壇我猜它不能)如果這是不可能的,替代方法可能是使用關聯容器,例如地圖或更簡單的配對"容器.
is there an easy way to output this to a file so that the first row contains the headings 'data1' and 'data2' followed by the actual contents. The function which outputs the data will be passed various different arrays so hardcoding the name of the heading is not possible - ideally I'd like to convert the variable name to some string and then output that string followed by the contents of the vector array. However, I'm not sure how to convert the variable name 'data1' to a string, or indeed if it can easily be done (from reading the forums my guess is it can't) If this is not possible an alternative might be to use an associative container such as map or perhaps more simply a 'pair' container.
pair<vector<double>,string> data1(10,'data1');
歡迎提出任何建議!
推薦答案
您可以使用預處理器stringify"#
做您想做的事:
You can use the preprocessor "stringify" #
to do what you want:
#include <stdio.h>
#define PRINTER(name) printer(#name, (name))
void printer(char *name, int value) {
printf("name: %s value: %d
", name, value);
}
int main (int argc, char* argv[]) {
int foo = 0;
int bar = 1;
PRINTER(foo);
PRINTER(bar);
return 0;
}
name: foo value: 0
name: bar value: 1
(對不起,printf
,我從來沒有掌握
的竅門.但這應該足夠了.)
(Sorry for printf
, I never got the hang of <iostream>
. But this should be enough.)
這篇關于將變量名轉換為 C++ 中的字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!