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;
for (int i = 0; i < 6; ++i)
//combining the string
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);
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:
This will most likely fix your problem. Also consider using
std::ostringstream instead of
std::stringstream here since you are only writing, not reading.
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.