如何使用 istringstream 从 c++ 中的字符串中读取双精度
How to read doubles from a string in c++ using istringstream
我是编程 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;
.
这两者都将帮助您避免命名空间污染,这使得调用正确的函数变得困难。
相关文章:
- 如何使用Luacneneneba API正确读取字符串和表参数
- 为什么 sscanf 无法从一个字符串中读取uint64_t和字符?
- 如何从字符串C++读取多个整数
- 使用字符串读取的字符串
- 从文件到字符串读取并传递到功能
- C++ cin 将字符串读取到 int 类型中返回 0
- 使用CIN和/或字符串读取带有混合输入的文本文件
- 将两个字符串作为一个字符串读取
- 如何将WCP 1252字符串读取为std::tstring
- 如何将字符串读取为字符串向量或将整数读取为整数向量
- 将一系列字符串读取到char数组中
- 如何在 c++ 中将文件中的段落作为单个字符串读取
- 从 txt 文件中将后缀表达式作为字符串读取
- C++银行项目;如何将一组字符串读取为单独的浮点数并添加它们
- 在 c++ 中循环字符串读取器
- 将字符串读取为命令行参数C++
- 如何在QT中使用QDomDocument对象将字符串读取为XML
- 使用Matio库将.mat文件中的字符串读取到C++中
- 作为字符串读取第一列数据文件
- 如何在字符串读取完成时停止c++的recv() ?