简体   繁体   中英

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?

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* ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM