Home > Blockchain >  How do I access individual lines in a string?
How do I access individual lines in a string?

Time:04-28

Say I have a string that goes:

"
199  
200  
208  
210    
200 
"

If I wanted to just access "208" for example, how would I do that after having read in the string input?

By the way, this is my code so far:

int main()
{
    int increase_altitude = 0;

    int previous = 10000;
    std::string s;
    while (std::getline(std::cin, s))
    {
        std::stringstream ss(s);
    }

CodePudding user response:

You can split the string into multiple lines and then access it like an array. For this purpose I'm using std::vector, but if you want to keep only unique lines you can use std::set.

TRY IT ONLINE

#include <string>
#include <iostream>
#include <vector>

static std::vector<std::string> split(const std::string &s, const std::string &del = "\n")
{
    std::vector<std::string> val;
    std::size_t start = 0;
    std::size_t end = s.find(del);
    while (end != std::string::npos)
    {
        val.push_back(s.substr(start, end - start));
        start = end   del.size();
        end = s.find(del, start);
    }
    val.push_back(s.substr(start, end - start));
    return val;
}

int main(void)
{
    std::string data = "199\n200\n208\n210\n200";
    auto lines = split(data);
    std::cout << lines[2] << std::endl; // 208 is at 2nd position, starting from 0
    return 0;
}

CodePudding user response:

If I understand that you want a way to locate and isolate "208" as a std::string. As you have started, once you read you complete string into a std::string you can use that to initialize a std::stringstream which will allow you to read one string at a time from the stringstream. You can then simply add each string to a std::vector<std::string> (if you need to store all individually), or you can perform the comparison for "208" there and avoid storing in a vector -- that's up to you.

Collecting all strings in a vector and then locating the "208" string, you can so something similar to:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>

int main () {
  
  std::vector<std::string> vs {};             /* vector<string> for strings */
  std::string s {"199\n200\n208\n210\n200"};  /* input string */
  std::string tmp;                            /* tmp to read stringstream */
  std::stringstream ss (s);                   /* initialize stringstream */
  
  while (ss >> tmp) {               /* loop reading tmp from stringstream */
    vs.push_back(tmp);              /* add string to vector of string */
  }
  
  for (const auto& str : vs)        /* loop over all strings */
    if (str == "208")               /* locate string that is 208 */
      std::cout << str << '\n';     /* output (or use) that string */
}

Example Use/Output

$ ./bin/str_multiline
208

If I missed understanding your goal, just drop a comment below and I'm happy to help further.

  •  Tags:  
  • c
  • Related