1

In this method,

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

When the user inputs a string - the filename to be taken in, I want to convert this string into a char so I can use it in other methods. How can I do this?

3
  • Instead of "convert this string into a char", do you perhaps mean convert it into a char pointer? Commented Apr 4, 2014 at 4:43
  • 2
    Making a char* from std::string is simple - call c_str() method on the string. Commented Apr 4, 2014 at 4:47
  • Your code shouldn't even compile on a respectable compiler. The last line: char *pattern = (char *)filename; is not valid. You could however grab a local, read-only char pointer to a string with: const char * pName = filename.c_str(); Bare in mind that the pointer is only valid inside the scope of the current function. Commented Apr 4, 2014 at 4:57

2 Answers 2

1

Just return the 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
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

You should use strcpy() instead. memcpy() won't copy the null terminator, thus leaving chFilNam in an invalid state to be used as a C string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.