使用从stringstream转换成字符串的ifstream
using ifstream from a stringstream converted in a string
我真的不明白为什么如果我使用 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;
}
您发布的代码有三个问题:
-
在写入
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
未初始化使用。在实际代码中,您可能将其初始化为每个文件中的行数。但是,您应该考虑使用这个SO答案来读取文件中的所有行。 -
在读取
ifstream
之前,您应该始终检查它是否成功打开。
相关文章:
- 将 ifstream 读取到 char* 以进行 int 和字符串转换
- 将字符串参数传递给 ifstream
- 如何使用 istream_iterator 从 ifstream 中读取带有空格的字符串?
- 为什么当 ifstream 创建从键盘读取字符串的文件时出现错误
- C ++ ifstream 无法读取字符串,并且在读取字符时出错
- 从带有ifstream和get()的文件中获取一个用引号表示的字符串
- 如何使用ifstream c ++从带有换行符的文件读取字符串
- C 使用字符串作为打开文件路径的ifstream错误
- 使用套接字编程的c++中的字符串流与ifstream(ofstream)
- C++如何将ifstream内容(来自文件)分配给具有偏移量的字符串(istreambuf_editor)
- C++ 如何从 ifstream 和 getline() 获取子字符串
- 用于中断哈希字符串的 ifstream
- ifstream 获取从字符到字符串的行更改输出
- ifstream get string的字符串进入数组
- ifstream在文件中获取错误的字符串
- 如何使用ifstream C++读取子字符串
- 通过 std::ifstream 从字符串中获取每个值
- std::getline 用于 ifstream,使用参数字符串或 char *
- 使用字符串作为打开文件路径时出现ifstream错误
- ifstream gcount在getline字符串重载时返回0