I really don't understand why if I use f.open(filename.c_str(),ios::in) works only if filename is a string defined as a string type, but not if filename is been converted from a stringstream type.
I need stringstream type, because I have to open different folders, so I use the program to create the wanted adresses.
Thankyou your cooperation.
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;
}
There are three issues with the code you posted:
In writing to the stringstream
, you should not include the std::endl
at the end. Otherwise, the resulting string for the filename
includes an extra newline character at the end, which most likely caused the file open to fail. Therefore, replace:
ss <<"/home/student/isoterma"<<n_gruppo<<"/pressione_vol"<<num_vol[i]<<".txt"<<endl;
with this:
ss <<"/home/student/isoterma"<<n_gruppo<<"/pressione_vol"<<num_vol[i]<<".txt";
This will most likely fix your problem. Also consider using std::ostringstream
instead of std::stringstream
here since you are only writing, not reading.
Your variable n_righe
is being used uninitialized. In your actual code, you probably have this initialized to the number of lines in each of your files. However, you should consider using this SO answer to read all the lines in your files.
You should always check to see if your ifstream
is opened successfully before reading from it. See this SO answer for that.