Putting words from a string into its own individual strings

So for an assignment I need to some how get "num_lines" and "logfile.txt" into its own individual strings. An idea I had involved individually checking each character in the string s and as long as it wasn't whitespace it would add continuously add it to a new string and upon detecting whitepace it would exit the loop. The problem is if there is whitespace infrom of "num_lines" it wouldn't work and the program would stop. How can I go about this?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

#include <iostream>
#include <fstream>
#include <vector>

using namespace std;


int main()
{
  string s = "  num_lines    logfile.txt";
  string u = "";
  string v = "";
  cout << s.size();

  while (s[i] != ' ')

}
Easiest way is to use stringstream for that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>


int main()
{
    std::string original = "  num_lines    logfile.txt";
    std::istringstream inp(original);
    std::string u;
    inp >> u;
    std::string v;
    inp >> v;
    std::cout << u << '\n' << v;
}
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <iterator>


int main()
{
    std::string original = "  num_lines    logfile.txt";
    std::istringstream inp(original);
    std::istream_iterator<std::string> it(inp);
    std::string u(*it++);
    std::string v(*it++);
    std::cout << u << '\n' << v;
}

I would if I could but sadly my prof wont let us use anything other iostream, vector, array, cmath, string, stream. So thats where it gets hard for me I think. Also forgot fstream.
Last edited on
Ok, using string facilities:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <vector>


int main()
{
    std::string s = "  num_lines    logfile.txt";
    //http://en.cppreference.com/w/cpp/string/basic_string/find_first_not_of
    //http://en.cppreference.com/w/cpp/string/basic_string/erase
    //Erasing leading spaces
    s.erase(0, s.find_first_not_of(' '));
    //http://en.cppreference.com/w/cpp/string/basic_string/substr
    //set u to first sequence of nonwhitespace characters in s
    std::string u = s.substr(0, s.find(' '));
    //Remove said sequence of characters
    s.erase(0, s.find(' '));
    //As line 12, getting rid of whitespaces
    s.erase(0, s.find_first_not_of(' '));
    //As line 15
    std::string v = s.substr(0, s.find(' '));;
    std::cout << u << '\n' << v;
}
Topic archived. No new replies allowed.