如何使用 istringstream 从 c++ 中的字符串中读取双精度

How to read doubles from a string in c++ using istringstream

本文关键字:字符串 读取 双精度 c++ 何使用 istringstream      更新时间:2023-10-16

我是编程 c++ 的新手。我正在尝试读取从文件中读取的字符串内的 75 个双精度。我正在尝试使用字符串流。

这是我到目前为止所拥有的:头文件:

#ifndef READPOINTS_H_INCLUDE
#define READPOINTS_H_INCLUDE
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std::istringstream;
.....
istringstream linestr;

CPP 文件: #include

void ReadPoints::grabPoin(const string& read_line, vector<doubles> PointVector){
linestr(read_line);
for(int i = 0; i < 75; i++){
 linestr >> value
 pointVector.push_back(value);
 }
}

当我编译此代码时,出现以下错误:

ReadPoints

.cpp: 在成员函数 'bool ReadPoints::grabPoint(const string&, std::vector&)':ReadPoints.cpp:48:19: 错误: 对 '(std::istringstream {aka std::basic_istringstream}) (const string&)' 的调用不匹配 Linestr(read_line);

谁能解释出什么问题以及为什么我接到不匹配的电话?

不要在标头中放置定义。目前,您有istringstream linestr;:将其放在一个 *.cpp 文件中,然后放在您的标头中,extern std::istringstream linestr(后者称为声明,与定义不同)。但是,无论如何,最好在函数本身中定义此字符串流。

将 *.cpp 中的linestr(read_line)替换为 std::istringstream line_str{ read_line },并从头文件中删除以下两行:using namespace std::istringstream;istringstream linestr;

您的代码现在应如下所示:

void ReadPoints::grabPoin(const string& read_line, vector<doubles> PointVector){
std::istringstream linestr{ read_line }; // if that doesn't work, use linestr(read_line) instead... note the () and {} have different meanings
for(int i = 0; i < 75; i++){
 linestr >> value
 pointVector.push_back(value);
 }
}

以下是其他一些提示:

  • 切勿将 using 指令放在标头中(即 using namespace
  • 不惜一切代价避免使用指令。如果您不想键入 std::istringstream ,请将其放在 *.cpp 文件中(是的,每个文件),如 using std::istringstream .
  • 如果必须使用 using 指令,则需要这样做:using namespace std; .

这两者都将帮助您避免命名空间污染,这使得调用正确的函数变得困难。