【问题标题】:Concerting char* to string to be read into file? [duplicate]将 char* 转换为要读入文件的字符串? [复制]
【发布时间】:2014-02-21 21:44:52
【问题描述】:

我正在尝试读取来自用户的输入,并且我知道我的方法需要一个 char*,但无论如何可以使 cin 的输入能够被该 char 使用? (查看 char* x 处的评论。)

string y;
cout << "Enter your file: ";
cin >> y;

char * x = //here is where the string needs to go. If I type in the actual address it works, but I need it to work when the user just cin's the address//

string line,character_line;
ifstream myfile;
myfile.open (x);
while(getline(myfile,line))
{
    if (line[0] != '0' && line[0] != '1')
    {
        character_line = line;
    }

}

【问题讨论】:

  • 使用 std::string::c_str() 转换为 c 风格的字符串

标签: c++ string char cin


【解决方案1】:
char * x = y.c_str();

一个简单的谷歌就会提供结果:)

【讨论】:

    【解决方案2】:

    您可以简单地使用 std::string 类的c_str() 方法。这有效:

    #include <fstream>
    #include <iostream>
    #include <string>
    
    int main(void) {
      std::string y;
      std::cout << "Enter your file: ";
      std::cin >> y;
      std::string line,character_line;
      std::ifstream myfile;
      myfile.open (y.c_str(), std::ifstream::in);
      while(getline(myfile,line))
      {
        if (line[0] != '0' && line[0] != '1')
        {   
          character_line = line;
        }   
    
      }
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-03
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      • 2018-03-27
      • 2013-05-13
      • 1970-01-01
      相关资源
      最近更新 更多