【发布时间】:2017-01-12 22:06:31
【问题描述】:
我真的不明白为什么如果我使用 f.open(filename.c_str(),ios::in) 仅当文件名是定义为字符串类型的字符串时才有效,但不是如果文件名是从字符串流类型转换而来的。
我需要stringstream类型,因为我要打开不同的文件夹,所以我用程序来创建想要的地址。
感谢您的合作。
using namespace std;
//c++ -o iso iso.cpp `root-config --cflags --glibs`
int main (int argc, char **argv)
{
int n_gruppo, n_righe;
cout << "write the number of the folder: " << endl;
cin >> n_gruppo;
int num_vol[6]={1,2,3,5,7,10};
for (int i = 0; i < 6; ++i)
{
//combining the string
stringstream ss;
ss <<"/home/student/isoterma"<<n_gruppo<<"/pressione_vol"<<num_vol[i]<<".txt"<<endl;
string filename = ss.str();//conversion sstream in string
cout << filename << endl;
double sumsq = 0, sum = 0, s;
//cicle of reading
ifstream f ;
f.open(filename.c_str(), ios::in);//ricorda di mettere '.c_str()' infondo se è una stringa
for (int io = 0; io < n_righe ; io++)
{
f >> s;
cout << "value N° " << io << " is" << s << endl;
sum += s;
sumsq += pow(s,2);
}
f.close();
}
return 0;
}
【问题讨论】:
-
这可以澄清事情吗? stackoverflow.com/questions/21034834/…
-
所以你是说 open(ss.str().c_str()) 不起作用?或者您是否尝试存储 str() 返回的临时对象中的 const char * 并稍后使用?
-
“仅在以下情况下有效”是什么意思? 如何在不满足前提条件的情况下不起作用?它不编译吗?它有什么行为?你期望什么行为?无论如何,创建一个minimal reproducible example。
-
我试图将文件夹的地址定义为一个字符串(例如 string s = "/home/student/folder1/file1.txt"),而不是将文件夹的名称和文件名(例如,strigstream ss;ss
标签: c++ ifstream stringstream