still learning

How do I read in a file, and then take a line from that file and split the line at a unique character?

It's quite simple. You read the line with getline, then use std::string::find to find the delimiter and then either use use std::string::assign to get the parts before and after the delimiter. Here is a simple example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <fstream>
#include <string>

  bool SplitString(const std::string& src, char sep, std::string& lhs, std::string& rhs)
  {
    if (src.size() < 3) // sep + min key + min value
      return false;
      
    std::string::size_type pos = src.find(sep);  
    if (pos == std::string::npos)
      return false;

    lhs.assign(src, 0, pos);
    rhs.assign(src, pos+1, std::string::npos);

    return true;
  }

int main()
{
  const char *filename = "filename.txt";

  std::ifstream src(filename);
  if (!src)
  {
    perror("File error: ");
    return -1;
  }
  std::string input, right, left;
  char delim = '=';
  std::getline(src, input);
  if (input.size() > 3)
  {
    if (SplitString(input, delim, left, right))
    {
      std::cout << left << '\t' << right;
    }
    else
    {
      std::cout << "No delimiter found.\n\n";
    }
  }
  return 0;
}
Last edited on
Topic archived. No new replies allowed.