-
Strings and Chars
I want to save some variables to a data text file, problem is the only way to do this i know of uses a "char *", I need to save some "String" type variables into the txt file that can be reloaded properly, I have tried.
Code:
String Test = "hello";
char * Test2 = Test.c_str();
but that doesn't load or save properly, I'm using Borland Visual Compiler, can anyone write me an example if it is possible?
-
Umm I would just try doing
char * NameOfSomething = "Cheese"
That's the way I would do it, and it should work
-
I don't wanna preset the variable like that, I have an external const char * with names within it that I want to use to set the other type of variables to begin with. But I seem to have to use a String else I get "|||[][]|" type of junk come up instead of the actual text, so I need to learn to find a way to safely output the String type variable/object to a text file and be able to reload it later..
-
Here is one solution.
Code:
// _TEXT is a macro in tchar.h for support of UNICODE
string sText = _TEXT("September 28, 2002");
size_t textSize = sText.size();
// Allocate one addition byte for NULL.
TCHAR *pText = new TCHAR[textSize + 1];
// _tcscpy() is defined in tchar.h.
// It is similar to strcpy() except it supports UNICODE.
_tcscpy(pText, sText.c_str());
pText[textSize] = NULL;
...
delete [] pText;
Kuphryn
-
any idea how you would be able to save the String to a text file and be able to load it back up without any problems?
-
>any idea how you would be able to save the String to a text file and be able to load it back up without any problems?
An std::string is simply a list of characters, if you use just about any output routine to write to the text file then it should work:
fout<<Test;
If it doesn't then maybe the problem is not in how you read and write or in the data type:
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
int main()
{
// Write a string to file
std::ofstream out ( "info.txt" );
if ( !out.is_open() ) {
std::cerr<<"Error opening file for writing"<<std::endl;
exit ( EXIT_FAILURE );
}
std::string test = "This is a test";
out<<test;
out.close();
// Read the string back
std::ifstream in ( "info.txt" );
if ( !in.is_open() ) {
std::cerr<<"Error opening file for reading"<<std::endl;
exit ( EXIT_FAILURE );
}
std::string input;
std::getline ( in, input );
std::cout<<"The string we saved is: "<< input <<std::endl;
// Start over, but read into an array
in.seekg ( 0, std::ios::beg );
char a_input[15];
in.getline ( a_input, 15 );
std::cout<<"The string we saved is: "<< input <<std::endl;
return EXIT_SUCCESS;
}
-Prelude