gpt4 book ai didi

c++ - 在 C++ 中,如何从字符串(或字符数组)中提取子字符串并将其写入字符串而不收到警告?

转载 作者:太空狗 更新时间:2023-10-29 20:37:12 25 4
gpt4 key购买 nike

在 C++ 中,我正在读取一个文件,其中的行类似于

     65-82 0.015 0.655

其中第一个是字符串(通常由数字组成,用短划线或逗号分隔,然后进行处理)和两个 float 。我目前正在使用以下代码阅读它们,其中 [line] 是一个字符数组:

std::string temp_string;
double temp_kb, temp_kt;
int res = sscanf(line, "%s %lf %lf",temp_string,&temp_kb,&temp_kt);

这会产生一个警告:

~/TEPInteraction.cpp:1002:76: warning: writing into constant object (argument 3) [-Wformat=]
int res = sscanf(line, "%s %lf %lf",temp_string.c_str(),&temp_kb,&temp_kt);
^

这当然是有道理的,因为 c_str() 返回一个常量指针。在没有警告的情况下执行此操作的正确方法是什么?

非常感谢,费迪南多

编辑:需要 res 的值来进一步执行一些控制,因此我将不得不简要地重写我的代码,以便它不使用它。没什么大不了的,但要等到明天。谢谢你们 :-) 非常感谢你们的帮助。

最佳答案

由于您的输入是用空格分隔的,因此您可以使用 >> 读取输入文件流的操作符。

std::ifstream fin("my_file_to_read");
std::string data;
double a, b;
fin >> data >> a >> b;

以上将花费

65-82 0.015 0.655

从文件中输入65-82进入data然后停在空格处。那么0.015被添加到 a然后停在空格处然后0.655被添加到 b .

由于您的输入以数字开头,如果您想确保每行有 3 个值,那么您需要使用 std::getline 从文件中读取整行.然后您可以将该行加载到 std::stringstream 中并检查提取是否成功。

std::ifstream fin("my_file_to_read");
std::string data, line;
double a, b;
std::getline(fin, line);
std::stringstream ss(line);
if (!(ss >> data >> a >> b))
{
//error handling code here
}

关于c++ - 在 C++ 中,如何从字符串(或字符数组)中提取子字符串并将其写入字符串而不收到警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35584507/

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