'struct std::string' has no member named 'c_string' [closed] - c++

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am receiving the error message 'struct std::string' has no member named 'c_string' in my code. I am basing the structure of this code off of a code in my textbook that successfully wrote a code with my compiler. What syntax errors could be causing this particular error? (it's on line 11)
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
string payroll = "table.dat";
ofstream MyCout;
MyCout.open(payroll.c_string());
if (MyCout.fail())
{
cout<<"Your file was not found";
exit(1);
}
MyCout<<setiosflags(ios::fixed)
<<setiosflags(ios::showpoint)
<<setprecision(2);
MyCout << "B Caldwell 555-88-2222"<<17.32<<37<<endl
<< "Next Line"<<0.00<<00<<endl;
<< "Next Line"<<0.00<<00<<endl;
MyCout.close();
cout<<"The file "<<payroll<<" has been successfully written"<<endl;
system ("Pause");
return 0;
}
I'm not sure if this helps or not, but here is the code that I am basing it off of
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<string>
#include<iomanip>
using namespace std;
int main()
{
string filename = "prices.dat";
ofstream outFile;
outFile.open(filename.c_str());
if (outFile.fail())
{
cout << "The file was not successfully opened" << endl;
exit(1);
}
outFile << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint)
<< setprecision(2);
outFile << "Mats " << 39.95 << endl
<< "Bulbs " << 3.22 << endl
<< "Fuses " << 1.08 << endl;
outFile.close();
cout << "The file " << filename << " has been successfully written."<<endl;
return 0;
}

std::string has no function or member called c_string, hence the exact compiler error. You can find plenty of information online about what members and functions are available to call on standard library objects, for instance here.
If you look closer at the code you're referencing, you'll see you meant to use c_str() instead.
Their code:
ofstream outFile;
outFile.open(filename.c_str());
Your code:
ofstream MyCout;
MyCout.open(payroll.c_string());
The solution:
ofstream MyCout;
MyCout.open(payroll.c_str());

Related

Can't open program because of int main error [duplicate]

This question already has answers here:
Two 'main' functions in C/C++
(13 answers)
Closed 3 years ago.
I know it is duplicated... I didn't understand any of the other threads. Literally just started to learn programming. Currently trying to learn C++ as my first language. Ran into this error, I did google it but I didn't really know what they were talking about. I looked at both of my "int main" things and they are exactly the same. No errors. I guess formatted wrong. Here is the code. I'm currently playing around with the std::count and variables, along with std:cin
#include <iostream>
int main()
{
std::cout << "Hello, how are you doing? I suppose you are only here to read this. Oh well.";
return 0;
}
int main()
{
std::cout << "Please feed me a number: " << "It can be any number."; // Asking human to enter a number.
int x{ }; // get number from keyboard and store it in value x
std::cin >> x; // recieved number and is now entering console
std::cout << "Thank you for feeding me " << x << '\n';
return 0;
}
A C++ program need only one main() function. This latter is called at program startup. Your code should look like this :
#include <iostream>
int main()
{
std::cout << "Hello, how are you doing? I suppose you are only here to read this. Oh well." << std::endl;
std::cout << "Please feed me a number: " << " It can be any number." << std::endl; // Asking human to enter a number.
int x{ }; // get number from keyboard and store it in value x
std::cin >> x; // recieved number and is now entering console
std::cout << "Thank you for feeding me " << x << std::endl;
return 0;
}
Here a link for more reading about the main() function.

I dont get the correct ouput [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to copy an specific word from a C array and put it into another c array so then later I can show the output, however when I execute the program the first function call works, (I get sprightful in the output/terminal)
"Copy \"sprightful\", should see \"sprightful\".\n";
however, when I call the function again it gives me this result (output/terminal) superhtful instead of super (since I specified in the argument, that I want to copy the first five characters). what's wrong?
#include <iostream>
#include <cstring>
#include <cctype>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
// function declarations
char* copy(char* destination, const char* source, size_t num);
int main()
{
const int WORDSIZE = 15;
char words[][WORDSIZE] = {"sprightful", "reason to row", "New York", "Bolton", "Frida", ""};
char word[WORDSIZE];
copy(word, words[0], sizeof(word) - 1);
cout << word << endl << endl;
copy(word, "Supercalifragilisticexpialidocious", 5);
cout << word << endl << endl;
return 0;
}
char* copy(char* destination, const char* source, size_t num)
{
strncpy(destination, source, num);
return destination;
}
You aren't clearing word in between the two function calls. On the second call it only overwrites the first 5 characters ("super"), and the rest is the result of your previous call.
#Brandon is correct. Try clearing word between your function calls:
int main()
{
const int WORDSIZE = 15;
char words[][WORDSIZE] = { "sprightful", "reason to row", "New York", "Bolton", "Frida", "" };
char word[WORDSIZE];
// Test the copy function
std::cout << "Copy \"sprightful\", should see \"sprightful\".\n";
copy(word, words[0], sizeof(word) - 1);
cout << word << endl << endl;
memset(&word[0], 0, sizeof(word)); //Clear the char array.
// Test the limit on the copy function
cout << "Copy \"Supercalifragilisticexpialidocious\", should see \"Super\".\n";
copy(word, "Supercalifragilisticexpialidocious", 5);
cout << word << endl << endl;
getchar();
return 0;
}

std::ofstream won't write to file (sometimes) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I've gone over many questions with the same or similar titles, I have changed the code in so many ways I can't even count.... I have an interesting problem.
I have a class for logging that is extremely simple and just writes stuff into a file. The exact same code works in the constructor, but will not work in the member function. I'm stripping out some irrelevant code, the rest is:
private:
std::string logfile_path_;
std::string program_name_;
std::string GetTimestamp() {
timeval tv;
gettimeofday(&tv, NULL);
char cTimestamp[24];
strftime(cTimestamp, sizeof(cTimestamp), "%F %T", std::localtime(&tv.tv_sec));
sprintf(&cTimestamp[19], ".%03d", (tv.tv_usec / 1000)); // write the miliseconds (microseconds/1000) into cTimestamp starting at the 20th character. %03d == pad with 0, for a minimum length of 3, an integer.
return cTimestamp; // function returns std::string so this will be implicitly cast into a string and returned.
}
public:
int log_level_;
SrxDsLog(std::string Logfile_path, std::string program_name, int log_level) {
log_level_ = log_level;
program_name_ = program_name;
logfile_path_ = Logfile_path;
std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
std::cout << "Logger started, Log file: " << logfile_path_ << std::endl;
logfile << "Logger started, Log file: " << logfile_path_ << std::endl;
return;
}
void WriteLog(std::string Log_message, int Severity = LOG_CRITICAL, std::string Function_name = "") {
if (Severity >= log_level_) {
std::cout << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
std::ofstream logfile(logfile_path_.c_str(), std::ios::out | std::ios::app);
logfile << GetTimestamp() << "|" << program_name_ << "|" << Function_name << "|" << GetSeverity(Severity) << "|" << Log_message << std::endl;
}
}
The question is why is it working in the constructor, but the exact same code is not working in the member function. The std::cout is writing the exact same log message I want, but it's not appearing in the file. The file contains a single line every time the program is run.
In an amazingly unsatisfying turn of events I voted to close my question.
The problem was apparently caused by undefined behavior in unrelated code. And that because I did something that's defined in C++11 but is not in C++03. Apparently you can't call constructors from constructors in C++03....
Because of that, and because the question didn't include the code that was actually at fault, the question seems incredibly bad.
Please close.
int log_level_;
The constructor fails to initialize this class member.
Subsequently, the comparison with this class member results in undefined behavior.

C++: Use Boost Serialization to write/read files [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I need to write/read a file that contains a std::map. The file must be read at the program start up (if it exists). Im using boost's fstream, but im getting this:
"terminate called after throwing an instance of 'boost::archive::archive_exception'
what(): input stream error"
Well, i really dont know what is happening.. these are my lines:
map<int64_t, int64_t> foo;
filesystem::path myFile = GetWorkingDirectory() / "myfile.dat";
[...............] // some code
filesystem::ifstream ifs(myFile);
archive::text_archive ta(ifs);
if (filesystem::exists(myFile)
{
ta >> foo; // foo is empty until now, it's fed by myFile
ifs.close();
}
What im doing wrong? Any idea?
Thanks.
P.S. Note that some lines after, i need to do the reverse action: write into myfile.dat the std::map foo.
EDIT: all works if i use std::ifstream, saving the file in the same dir where im running the Application. But using boost and his path, something goes wrong.
I'm a bit miffed. You're clearly using Boost Serialization (the archive/ headers are part of this library) but somehow you're not saying anything about that. Because it's so easy to demonstrate:
Live On Coliru
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/serialization/map.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace boost;
int main() {
std::map<int64_t, int64_t> foo;
filesystem::path myFile = filesystem::current_path() / "myfile.dat";
if (filesystem::exists(myFile))
{
filesystem::ifstream ifs(myFile/*.native()*/);
archive::text_iarchive ta(ifs);
ta >> foo; // foo is empty until now, it's fed by myFile
std::cout << "Read " << foo.size() << " entries from " << myFile << "\n";
} else {
for (int i=0; i<100; ++i) foo.emplace(rand(), rand());
filesystem::ofstream ofs(myFile/*.native()*/);
archive::text_oarchive ta(ofs);
ta << foo; // foo is empty until now, it's fed by myFile
std::cout << "Wrote " << foo.size() << " random entries to " << myFile << "\n";
}
}
Prints
Wrote 100 random entries to "/tmp/myfile.dat"
And on second run:
Read 100 entries from "/tmp/myfile.dat"

Error : double free or corruption (fasttop) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I try since a few day to make this little code but it doesn't work. I see a lot of question about this problem but i didn't find an answer to mine.
Here is the code for Voiture.cpp :
#include <iostream>
using namespace std;
#include <string.h>
#include "modele.h"
Voiture::Voiture()
{
Nom=NULL;
setNom("Default");
VoitChoix=Modele();
cout << "COnstructeur default" << endl;
}
Voiture::Voiture(const char* N,const Modele V)
{
Nom=NULL;
setNom(N);
setModele(V);
cout << "COnstructeur initialisation" << endl;
}
Voiture::Voiture(const Voiture& V)
{
Nom=NULL;
setNom(V.getNom());
setModele(V.getModele());
cout << "COnstructeur copie" << endl;
}
Voiture::~Voiture()
{
if(Nom)
{
cout << "Voiture : Destruction de" << Nom << endl;
delete [] Nom;
}
}
Here is the code for Modele.cpp :
#include <iostream>
#include <string.h>
using namespace std;
#include "modele.h"
Modele::Modele()
{
Nom=NULL;
setNom("Default");
Puissance=0;
Diesel=true;
PrixDeBase=0;
cout << "COnstructeur default" << endl;
}
Modele::Modele(const char* N,const int P,const bool D,const float PDB)
{
Nom=NULL;
setNom(N);
setPuissance(P);
setDiesel(D);
setPrixDeBase(PDB);
cout << "COnstructeur initialisation" << endl;
}
Modele::Modele(const Modele& M)
{
Nom=NULL;
setNom(M.getNom());
setPuissance(M.getPuissance());
setDiesel(M.isDiesel());
setPrixDeBase(M.getPrixDeBase());
cout << "COnstructeur copie" << endl;
}
Modele::~Modele()
{
if(Nom)
{
cout << "Modele: Destruction de" << Nom << endl;
delete [] Nom;
}
}
Here is the code for main.cpp :
int main()
{
cout << "(1) ***** Test du constructeur par defaut de Voiture *****" << endl;
{
Voiture voiture;
voiture.Affiche();
}
}
I don't put all the code, just where i have the problem.
Thanks ! :(
One obvious problem is that you're missing a user-defined assignment operator:
VoitChoix=Modele();
This calls the assignment operator, not copy constructor. Since you do not have a user-defined assignment operator for Modele, then you will have issues on destruction of VoitChoix. More specifically, you are assigning all of the values that Modele() has created to VoitChoix.
So you have two instances that have the same pointer value for Nom. When the temporary Modele() goes out of scope, it will call the destructor, thus deleting Nom. When VoitChoix goes out of scope, it will attempt to delete the same pointer value for Nom. Thus the double delete error.
The user defined assignment operator for Modele would have the following signature:
Modele& operator=(const Modele&);
You will need to implement this function before going any further. This can be done easily using the copy/swap idiom: What is the copy-and-swap idiom?
Also, please follow the rule of three when creating your class: What is The Rule of Three?