使用从stringstream转换成字符串的ifstream

using ifstream from a stringstream converted in a string

本文关键字:字符串 ifstream 转换 stringstream      更新时间:2023-10-16

我真的不明白为什么如果我使用 f.p open(filename.c_str(),ios::in)仅当filename是定义为字符串类型的字符串时有效,但如果filename是从stringstream类型转换而来,则不有效。

我需要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;
}

您发布的代码有三个问题:

  1. 在写入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,因为你只是在写,而不是阅读。

  2. 您的变量n_righe未初始化使用。在实际代码中,您可能将其初始化为每个文件中的行数。但是,您应该考虑使用这个SO答案来读取文件中的所有行。

  3. 在读取ifstream之前,您应该始终检查它是否成功打开。