C ++:cin>> *字符 [英] C++: cin >> *char

查看:331
本文介绍了C ++:cin>> *字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我目前正在编写一个行编辑器,作为有关I/O的学习项目,编写文件等.它是用C ++编写的,我目前正在尝试写出用户选择的文件.我已经实现了CLI参数,但是目前我不知道如何以编程方式实现指定要写入的文件.

So, I'm currently writing a line editor as a learning project on I/O, writing files, and the like. It is written in C++, and I am currently trying to write out to a file of the user's choosing. I have CLI arguments implemented, but I currently have no idea how to implement an in program way of specifying the file to write to.

char *filename;
if (argc >= 2){
        filename = argv[1];
} else{
        cout << "file>";
        cin >> filename;
        cin.ignore();
}

当我使用命令行参数时,这种方法效果很好.但是,无论何时不执行,只要启动程序,它就会出现分段错误.我使用实际文件名的位置在save命令中:

This works perfectly well when I use command line arguments; however, whenever I do not, as soon as I start the program, it Segmentation Faults. The place where I use the actual filename is in the save command:

void save(char filename[], int textlen, string file[]){
        ofstream out(filename);
        out << filestring(textlen, file);
        out.close();
}

哪个也能很好地工作.有什么办法可以帮助我吗?要查看完整的源代码,请访问 https://github.com/GBGamer/SLED

Which also works perfectly well. Is there any way you can help me? Full source code, for review, is up on https://github.com/GBGamer/SLED

推荐答案

问题是char* filename只是指向某些包含字符的内存的指针.它本身不拥有任何内存. 当您使用命令行参数时,程序会将该字符串存储在某处,并获得指向它的指针.当您尝试使用cin >> filename进行读取时,实际上没有任何地方可以存储读取的数据.

The problem is that char* filename is just a pointer to some memory containing characters. It does not own any memory itself. When you use the command line argument, the program handles storing that string somewhere, and you get a pointer to it. When you try to read using cin >> filename there isn't actually anywhere to store the read data.

解决方案:将char* filename替换为std::string filename(和#include <string>).

Solution: Replace char* filename with std::string filename (and #include <string>).

然后打开输出文件,您需要一个c样式的字符串(以空终止的char数组). std::string具有此功能.你会写

Then to open the output file, you need a c-style string (null terminated char array). std::string has a function for this. You would write

std::ofstream out(filename.c_str());
                           ^^^^^

或者,实际上,如果您可以使用具有c ++ 11功能的最新编译器,则甚至不需要使用c_str().添加了新的 std::ofstream构造函数以接受std::string

Or, in fact, if you can use a recent compiler with c++11 features, you don't even need to use c_str(). A new std::ofstream constructor has been added to accept a std::string.

这篇关于C ++:cin&gt;&gt; *字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆