#include <string>
#include <sstream>
#include <fstream>
#include <iostream>
#include "itemManager.hpp"
void item::loadItem(int itemID){
char name[30]; //temporary buffer to load string off file
//load file "../itemArchive/1.txt" for example
std::string filename;
filename.assign("../itemArchive/" + itemID);
filename.append(".txt");
std::ifstream file;
file.open(filename.c_str());
//load the string off the file
std::cin.getline(name, 30); //I am assuming this is the issue
std::string s_name(name, 30); //convert the char array to a string
this->name = s_name; //put that string into the class variable
}
Those are the two relevant files to the situation at hand, basically I would like to know if I am taking an incorrect approach at this. I am trying to load the first string from the text file. The file is in a folder relative to the executable called itemArchive. The filename is 1.txt. I stride to create a program that will load an item file for a game into the application by simply loading it by loadItem(1); for example. At the moment the code outputs illegible characters.
Thank you in advance for any help you can give. :).
Why are you doing all the fancy stuff with a char[] buffer? Just use getline() to read directly into the string: std::getline(std::cin, this->name); // read one line into name
I did not realize I could do that. Thank you very much, I will try it.
edit: Thank you, that helped some, but basically at this point what it's doing is returning blank, so I'm assuming there is also an issue with how I am creating the string, I don't think it can find the file.
Where are you keeping the files? ../itemArchive/1.txt needs to be relative to the working directory of the program (usually wherever the executable is located).
Correct, that is where I have it. I moved the txt file to the working directory, out of the sub-directory. It is now finding the file with the following code:
My only issue now is that it is returning blank still, even with finding the file, plus I would like to get it to where it can find the file within the sub-directory. I also tried to load the file from the sub-directory using the converter on the int value, and it once again cannot find the file.
edit: I got the code working for the most part. When it is in the working directory it works properly, but I want to get it to where it works being in the sub-directory.