gpt4 book ai didi

c++ - 在 C++ 中使用 strtok

转载 作者:太空宇宙 更新时间:2023-11-04 15:47:52 25 4
gpt4 key购买 nike

我正在尝试读取一个输入(时间和价格)为:12:23:31 的文件
67 12:31:23 78 [...]
我创建了一个 struct 来保存小时的值,分钟和秒。我使用 strtok 来标记各个值并使用 atof 来存储它们。但是,当我尝试时出现错误标记时间:无法将参数 1 的 std::string' 转换为 'char*' 到 'char*'

struct time
{
int hours;
int minutes;
int seconds;
double price;
};

int main()
{
string file, input;
time* time_array;
char* tok;

cout << "Enter a file name to read input: ";
cin >> file;

ifstream file_name(file.c_str());

file_name >> input;
file_name >> input;

//while(!file_name.eof())
for(int i = 0; i < 4; i++)
{
time_array = new time;
file_name >> input;
tok = strtok(input, ":"); //ERROR HERE
while(tok != NULL)
{
*time_array.hours = atof(tok[0]);
*time_array.minutes = atof(tok[1]);
*time_array.seconds = atof(tok[2]);
}
file_name >> input;
*time_array.prine = atof(input);
}
}

最佳答案

我根本不会为这项工作使用strtok1。如果要使用类 C 工具,则使用 fscanf 读取数据:

// note there here `file_name` needs to be a FILE * instead of an ifstream.
fscanf(file_name, "%f:%f:%f %f", &hours, &minutes, &seconds, &price);

但大多数编写 C++ 的人更喜欢类型安全的东西。一种可能性是使用本质上相同的格式字符串来使用 Boost.format 读取数据。 .

另一种可能性是使用流提取器:

char ignore1, ignore2;
file >> hours >> ignore1 >> minutes >> ignore2 >> seconds >> price;

至于这是做什么的/它是如何工作的:每个提取器从输入流中读取一个项目。 float 的提取器分别读取一个数字。 char 的提取器各读取一个字符。在这种情况下,我们希望看到:99:99:99 99,其中 9 表示“一个数字”。因此,我们读取了一个数字、一个冒号、一个数字、一个冒号、一个数字和另一个数字(提取器会自动跳过空格)。两个冒号被读入 char 变量,可以忽略,或者您可以检查它们是否真的是冒号以验证输入数据的格式是否正确。

这是该技术的一个完整的、可编译的演示:

#include <iostream>


int main() {
float hours, minutes, seconds, price;
char ignore1, ignore2;

std::cin >> hours >> ignore1 >> minutes >> ignore2 >> seconds >> price;

std::cout << "H:" << hours
<< " M:" << minutes
<< " S:" << seconds
<< " P:" << price << "\n";
return 0;
}

当然还有更多的可能性,但至少那些是一些合理的。


  1. 老实说,我不确定是否有任何的工作我会使用strtok,但有一些我可能至少有点想做,或者希望 strtok 的设计不要那么糟糕,这样我就可以使用它了。然而,在这种情况下,我什至看不出有太多理由使用任何类似于 strtok 的东西。

关于c++ - 在 C++ 中使用 strtok,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13746863/

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