字符串作为C ++ Outfile中的文件名

时间:2014-12-09 04:08:52

标签: c++ string file-io ofstream

有人可以告诉我为什么以下不起作用?

#include <fstream.h>  
#include <iostream.h>

std::string data, newtitle, body;
ofstream outfile;

int main()
{
   cout << "enter body of note: ";
   cin >> body;

   cout << "enter title of note: ";
   cin >> newtitle;

   data =  newtitle + ".dat";

   outfile.open(data, ios::out);
   outfile << body << endl;
   outfile.close();               

   system("pause");
   return 0;
}

问题似乎源于尝试合并newtitle.dat

由于

2 个答案:

答案 0 :(得分:3)

首先,

#include <fstream.h>  

错了,应该只是

#include <fstream>  

与其他标题相同。

其次,你需要

#include <string>

使用std::string

第三,如果你正在为C ++ 03进行编译,那么没有构造函数使用std::string。但是这在C ++ 11中得到了修复。


提示#1: 您不需要system( "pause" )。在Visual Studio中,只需使用 Ctrl + F5 即可运行该程序。然后控制台窗口保持。

或者,只需从命令行运行程序。


提示#2: 通过将变量声明为尽可能接近首次使用,可以避免很多麻烦。例如,通过将std::string data, newtitle, body;移动到main,并且尽可能晚地将其声明,您可以确保没有其他代码混淆这些变量,并且完全清楚初始值是什么,等等。


提示#3: return 0;末尾您不需要main:这是默认设置。

答案 1 :(得分:0)

std :: cin 空格分隔输入字符串

如果您将此文本输入第一个cin

  

abc def

body变量将 abc ,newtitle将 def 。在这种情况下,std :: getline可能就是答案