Kyle
Kyle

Reputation: 43

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

I am new to programming c++. I am trying to read 75 doubles that are inside of a string that I read from a file. I am trying to use istringstream.

This is what I have so far: Header File:

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

CPP FILE: #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);
 }
}

When I compile this code I get the following error:

ReadPoints.cpp: In member function ‘bool ReadPoints::grabPoint(const string&, std::vector&)’: ReadPoints.cpp:48:19: error: no match for call to ‘(std::istringstream {aka std::basic_istringstream}) (const string&)’ linestr(read_line);

Can anyone explain what is wrong and why I am getting the no match for call?

Upvotes: 0

Views: 863

Answers (1)

cjdb
cjdb

Reputation: 46

Don't place a definition inside a header. Currently, you've got istringstream linestr;: place this in exactly one *.cpp file, and then in your header, extern std::istringstream linestr (the latter is called a declaration, which is different to a definition). However, this stringstream is best defined in the function itself anyway.

Replace linestr(read_line) in your *.cpp with std::istringstream line_str{ read_line } and remove these two lines from your header file: using namespace std::istringstream; and istringstream linestr;.

Your code should now look like this:

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);
 }
}

Here's a couple of other tips:

  • Never place a using directive inside a header (that is, using namespace)
  • Avoid using directives at all costs. If you don't want to type std::istringstream, place it inside your *.cpp files (yes, each of them), as using std::istringstream.
  • If you must use a using directive, you need to do it like so: using namespace std;.

Both of these will help you to avoid namespace pollution, which makes calling the right functions difficult.

Upvotes: 0

Related Questions