簡體   English   中英

如何使用istringstream從C ++中的字符串讀取雙精度

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

我是編程C ++的新手。 我正在嘗試讀取從文件讀取的字符串中的75個雙打。 我正在嘗試使用istringstream。

這是我到目前為止所擁有的:頭文件:

#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;

這兩個都將幫助您避免名稱空間污染,這將導致調用正確的函數變得困難。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM