gpt4 book ai didi

c++ - 读取文件时如何将字符串转换为字符数组?

转载 作者:行者123 更新时间:2023-11-28 06:31:26 24 4
gpt4 key购买 nike

我想将字符串从输入文件转换为字符数组以标记文件。这段代码可能还有其他问题,但就目前而言,编译器会提示“将‘const char*’赋值给‘char [100]’时类型不兼容”。

string filename = "foo.txt";
ifstream data(filename.c_str());
string temp;
char str[100];
char* pch;
while (getline(data, temp)){
str = temp.c_str();
pch = strtok(str, " ,.");
while (pch != NULL){
cout << pch << endl; //Or something else, Haven't gotten around to this part yet.
pch = strtok (NULL, " ,.");
}
}

最佳答案

我知道这不能回答你的问题,但答案确实是:换一种方式,因为如果你继续做你正在做的事情,你就会陷入一个受伤的世界......

你可以在没有任何魔数(Magic Number)或原始数组的情况下处理这个问题:

const std::string filename = "foo.txt";
std::ifstream data(filename.c_str());
std::string line;
while(std::getline(data, line)) // #include <string>
{
std::string::size_type prev_index = 0;
std::string::size_type index = line.find_first_of(".,");
while(index != std::string::npos)
{
std::cout << line.substr(prev_index, index-prev_index) << '\n';
prev_index = index+1;
index = line.find_first_of(".,", prev_index);
std::cout << "prev_index: " << prev_index << " index: " << index << '\n';
}
std::cout << line.substr(prev_index, line.size()-prev_index) << '\n';
}

此代码不会赢得任何节拍或效率竞赛,但肯定不会因意外输入而崩溃。 Live demo here (using an istringstream as input instead of a file) .

关于c++ - 读取文件时如何将字符串转换为字符数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457550/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com