如何将ifstream或字符串输入转换为char?

时间:2014-04-04 04:42:07

标签: c++ string char

在这种方法中,

void mainRoutine(char *pattern, string searchPattern)
{
        cout << "Please enter the string pattern to be searched: " << endl;
        getline(cin, searchPattern);
        ifstream filename(searchPattern.c_str());
        while(filename.good() && filename.peek() != EOF)
        {
                cout << (char)filename.get();
        }
        cout << "\n";
        char *pattern = (char *)filename;
}

当用户输入一个字符串 - 要引入的文件名时,我想将此字符串转换为char,以便我可以在其他方法中使用它。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

只需返回std::string

即可
std::string mainRoutine()
{
  std::string searchPattern;
  std::cout << "Please enter the string pattern to be searched: \n";
  std::cin >> searchPattern;

  std::cout << std::ifstream(searchPattern).rdbuf() << '\n';
  // searchPattern.c_str() if not using c++11

  return searchPattern
}

答案 1 :(得分:0)

char* chFilNam = new char[fileName.length() + 1];
memcpy(chFilNam,fileName.c_str(),fileName.length());