如何将用户输入存储为 char*
How do I store user input as a char*?
在我的主方法中,
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*
中存储东西......
相关文章:
- 如何在cpp.中使用协议缓冲区存储大缓冲区/数组(char/int)
- 使用 char* 存储数据和产生的错误
- 如何声明一个必须在C++中同时存储int和char值的2D数组
- 如果char可以在C++中存储数字,为什么我们需要int
- C++17:unique_ptr<char[]> 和 shared_ptr<char[] 之间的指针存储差异>
- 将.txt文件存储到 char* 2d 矢量C++中
- 使用 std::vector<char> 作为异构记录的存储是否安全?
- 将 C++ 字符串存储到 char* 向量中
- 哪一个更适合存储字符、矢量<char>或字符串?
- C++ 存储来自 char* 函数的字符列表
- char*中存储的返回int值(0-255)给出了负值
- 将字符指针按顺序存储在 map 中 std::map<char*, int> mymap。将其存储为字符或字符串不是一个选项
- 使用C 中字符串标头的getline()函数将第一个char存储在字符串对象中
- 当您声明指向char数组的指针时,存储在内存中
- 通过无符号 char 别名进行对象访问,加载和存储时会发生什么?
- 在int到char转换期间,int将在char中存储在char中,如果int太大,将在char中存储的值
- C :占用更多内存,将单个字符作为char或字符串存储
- 使用 char*array 存储条形图的条形图,以便我可以动态制作它并作为字符串返回
- 将int转换为十六进制并将其存储到char缓冲区中
- 使用 char* 存储整数