使用转换为字符串的字符串流中的 ifstream
using ifstream from a stringstream converted in a string
我真的不明白为什么如果我使用 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;
}
您发布的代码存在三个问题:
在写给 stringstream
时,您 不应在末尾包含 std::endl
。否则,filename
的结果字符串在末尾包含一个额外的换行符,这很可能导致文件打开失败。因此,替换:
ss <<"/home/student/isoterma"<<n_gruppo<<"/pressione_vol"<<num_vol[i]<<".txt"<<endl;
有了这个:
ss <<"/home/student/isoterma"<<n_gruppo<<"/pressione_vol"<<num_vol[i]<<".txt";
这很可能会解决您的问题。还可以考虑在这里使用 std::ostringstream
而不是 std::stringstream
,因为您只是在写,而不是在阅读。
您的变量 n_righe
未初始化就被使用。在您的实际代码中,您可能已将其初始化为每个文件中的行数。但是,您应该考虑使用 this SO answer 来读取文件中的所有行。
在读取之前,您应该始终检查 ifstream
是否已成功打开。请参阅 this SO answer。
我真的不明白为什么如果我使用 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;
}
您发布的代码存在三个问题:
在写给
stringstream
时,您 不应在末尾包含std::endl
。否则,filename
的结果字符串在末尾包含一个额外的换行符,这很可能导致文件打开失败。因此,替换:ss <<"/home/student/isoterma"<<n_gruppo<<"/pressione_vol"<<num_vol[i]<<".txt"<<endl;
有了这个:
ss <<"/home/student/isoterma"<<n_gruppo<<"/pressione_vol"<<num_vol[i]<<".txt";
这很可能会解决您的问题。还可以考虑在这里使用
std::ostringstream
而不是std::stringstream
,因为您只是在写,而不是在阅读。您的变量
n_righe
未初始化就被使用。在您的实际代码中,您可能已将其初始化为每个文件中的行数。但是,您应该考虑使用 this SO answer 来读取文件中的所有行。在读取之前,您应该始终检查
ifstream
是否已成功打开。请参阅 this SO answer。