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

How do I store user input as a char*?

本文关键字:char 存储 输入 用户      更新时间:2023-10-16

在我的主方法中,

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

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

没有

除非您想处理字符串分配、解除分配和所有权,以及缓冲区溢出和安全问题,否则您只需使用 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*中存储东西......