user3205160
user3205160

Reputation: 137

How do I store user input as a char*?

In my main method,

int main()
{
        char *words = (char *)"GETGETYETYET";
        char *pattern = (char *)"GET";
        return 0;
}

Instead of *words and *pattern being a predefined char set, I want to get user input, the user types in the name of a .txt file, and I want the strings in that .txt file to be stored as (char *). How can I do this?

Upvotes: 0

Views: 1107

Answers (1)

Massa
Massa

Reputation: 8972

You don't.

Unless you want to deal with string allocations, deallocations, and ownerships, with buffer overruns and security problems, you just use std::string...

Like this:

#include <iostream>
#include <string>

int main() {
  std::string a = "abcde";
  std::string b;
  getline(std::cin, b);
  std::cout << a << ' ' << b;
  return 0;
}

Suppose your strings are on the file x.txt, one per line:

#include <iostream>
#include <string>
#include <fstream>

int main() {
  std::string line;
  std::ifstream f("x.txt");
  while( std::getline(f, line) )
    std::cout << ' ' << line << '\n';
  return 0;
}

The point here being that you really don't want to store things in char*...

Upvotes: 2

Related Questions