C++: cin >> *char

浪尽此生 提交于 2020-04-13 17:23:35

问题


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();
}

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();
}

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


回答1:


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.

Solution: Replace char* filename with std::string filename (and #include <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());
                           ^^^^^

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.




回答2:


Your filename variable points to argv[1] when command line argument is provided, it does not need memory to be allocated but when going in else block, you have not allocated memory to filename. Its just a pointer.

Use malloc to assign filename some memory then take user input.

filename = (char *)malloc(sizeof(char)*(FILE_NAME_LENGTH+1))


来源:https://stackoverflow.com/questions/17501092/c-cin-char

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!