0

test.txt :
18 19 20
21 22 23
22 23 24
23 24 25
24 25 26
25 26 27
28 29 30
29 30 31

I want to read in the integers in test.txt as strings then create a vector of 3 ints.
If that makes sense, so the output is a vector looking like:
18 19 20, 21 22 23, 22 23 24, 23 24 25, 24 25 26, 25 26 27, 28 29 30, 29 30 31

Heres my code:

#include "test.txt"
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <vector>
#include <array>

using namespace std;

struct M
{
  int x;
  int y;
  int z;
};

int main(){
  ifstream file;
  file.open("test.txt");

  string value;
  M XYZ;
  vector<M> Vec;

  if (file){
    while (getline(file, value)){
      XYZ.x = stoi(value);
      if (value == " ")
        XYZ.y = stoi(value);
      if (value == " ")
        XYZ.z = stoi(value);
    }
    Vec.push_back(XYZ);
  }
  else
    cout << "Error openning file." << endl;

  for (int i = 0; i < Moves.size(); i++)
    cout << Moves[i] << endl;

  return 0;
}
2
Contributors
1
Reply
10
Views
2 Years
Discussion Span
Last Post by mike_2000_17
0

The std::stringstream class is what you can use for this. Once you have a string (from getline) you can create a stringstream object that operates on it. At this point, the stringstream is, as its name implies, a regular io-stream that uses the underlying string as its buffer (read or write). This is the recommended way to do stream-like operations on strings (such as reading numbers from it). See stringstream docs.

When you read numbers from a stream, it already takes care of skipping spaces (and other "empty" characters) and reads only the first valid number from the stream. This means that you can read all the numbers from a single line, one after the other, as so:

while (getline(file, value)){
  // Create stream for the 'value' string:
  stringstream ss(value);
  // Read numbers from the stringstream:
  ss >> XYZ.x >> XYZ.y >> XYZ.z;
}

The above code does not check for error conditions like having an empty line, or having an otherwise invalid line (not three numbers), but that could be done too, of course.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.