' struct std :: string'没有名为' c_string'

时间:2017-11-16 02:11:03

标签: c++

我收到错误消息' struct std :: string'没有名为' c_string'在我的代码中。我将这段代码的结构基于我的教科书中的代码,该代码用我的编译器成功编写了代码。什么语法错误可能导致此特定错误? (它在第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;
       }

我不确定这是否有帮助,但这是我基于它的代码

#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; 
}

1 个答案:

答案 0 :(得分:2)

std::string没有名为c_string的函数或成员,因此确切的编译器错误。您可以在线找到大量有关可用于调用标准库对象的成员和函数的信息,例如here

如果您仔细查看您引用的代码,您会发现您打算使用c_str()代替。

他们的代码:

ofstream outFile;
outFile.open(filename.c_str());

您的代码:

ofstream MyCout;
MyCout.open(payroll.c_string());

解决方案:

ofstream MyCout;
MyCout.open(payroll.c_str());