我在让非常基本的命令提示符文本处理器工作时遇到问题。ofstream() 的问题
I'm having trouble getting a very basic command prompt text processor working. Problems with ofstream()
到目前为止,我已经让我的程序顺利地从用户那里获取文件位置和文件名。问题来自当我尝试使用用户提供的文件位置创建ofstream
对象时。 我基本上使用字符串库中的append()
函数使文件的位置采用我正在使用的标准格式c:usersusermy documents"file"
。 我已经在没有ofstream
对象的情况下测试了代码,事情似乎很好。 所以我只是不确定为什么 ofstream 对象不会引用字符串变量指定的文件位置 - filelocation。
目前,程序应该只是在某处创建一个包含 Hello 的文件,但这并没有发生,代码拒绝编译。我计划在更远的地方获得用户输入,但这是我在继续之前需要克服的一个小障碍。
#include <fstream>
#include <string>
#include <iostream>
using namespace std ;
int main()
{
string text = "Hello" ;
string title ;
string usertitle ;
string filelocation = "C:/Users/" ;
string user ;
cout << "Input a title for your file: " ;
cin >> title ;
title.insert(title.length() , ".txt" ) ;
cout << "Your title is: " << title << endl ;
cout << endl << "Input the username associated with your computer (Caps Sensitive): " ;
cin >> user ;
filelocation.append( user ) ;
filelocation.append("/My Documents/") ;
filelocation.append(title) ;
filelocation.insert(0, """) ;
filelocation.insert(filelocation.length() , """ ) ;
cout << "Your chosen file name and location is: " << filelocation << endl ;
ofstream writer( filelocation.c_str() ) ;
if (! writer )
{
cout << "Error opening file for output" << endl ;
return -1 ; //Signal an error then exit the program
}
else
{
writer << text << endl ;
writer.close() ;
}
return 0 ;
}
提前感谢您提供的任何帮助!
您是否检查了构造函数std::ofstream
参数?我认为这是一个const char *
.
构造函数声明为
explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);
所以在你的情况下,你使用std::string
作为参数,它应该是
std::ofstream writer(filelocation.c_str());
相关文章:
- 编译包含字符串的代码时遇到问题
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 在 for 循环中查找问题时遇到困难
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 从其他类访问类时遇到问题
- 打印问题.我在数组中打印值时遇到一些问题
- 使用静态成员声明类时遇到问题
- C++ 填充数组时遇到问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 我在使用C++文件时遇到了一些问题
- 在将字符串放入字符串向量时遇到问题?
- 余数除法和不允许除以零 (c++) 时遇到问题
- 我在C++中使用 getline() 函数时遇到问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 在我的四叉树实现中遇到问题
- 在 c++ 中循环遍历数组时遇到问题
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 使用 MinGW 在 Windows 上构建 GLEW 时遇到问题
- 编译 Cilk Plus 程序时遇到问题