【问题标题】:using ifstream from a stringstream converted in a string使用字符串流中的 ifstream 转换为字符串
【发布时间】: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


【解决方案1】:

您发布的代码存在三个问题:

  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 未初始化使用。在您的实际代码中,您可能已将其初始化为每个文件中的行数。但是,您应该考虑使用this SO answer 来读取文件中的所有行。

  3. 在读取ifstream 之前,您应该始终检查它是否已成功打开。请参阅this SO answer

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2014-06-25
    • 2023-03-24
    相关资源
    最近更新 更多