如何将用户输入存储为char *?

时间:2014-04-05 01:41:22

标签: c++ string char

在我的主要方法中,

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

我想获取用户输入,用户输入.txt文件的名称,而不是* words和* pattern是预定义的字符集,我希望将.txt文件中的字符串存储为( char *)。 我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

除非你想处理字符串分配,解除分配和所有权,以及缓冲区溢出和安全问题,否则你只需使用std::string ...

像这样:

#include <iostream>
#include <string>

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

假设您的字符串位于文件x.txt上,每行一个:

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

这里的重点是你真的不想在char* ...

中存储东西