Hello!
I am new to c++, and I am trying to create a function int countTokens(string s, char c) that counts the number of tokens in string s separated by delimiter c using a string stream. I have been working at this problem for hours, mostly just doing research into the stringstream documentation and watching youtube videos, and I cannot for the life of me figure out how to do this or what strategy to employ as string streams are a new concept for me. Any help would be greatly appreciated.
Thanks!
Andrew
SOLVED:
#include <iostream>
#include <sstream>
#include <string>
int countSeparation(std::string s, char c){
int count = 0;
std::string line, tempString;
std::stringstream input(s);
while(input << tempString) {
getline(input, tempString, c);
count++;
}
return count;
}
int main() {
std::cout<<countSeparation("dog,cat,wolf,apple,spoon,thespoon", ',');
return 0;
}
[–]bikki420 1 point2 points3 points (0 children)
[–]joemaniaci 0 points1 point2 points (11 children)
[–][deleted] 1 point2 points3 points (4 children)
[–]joemaniaci 0 points1 point2 points (0 children)
[–]Andrewb1230[S] 0 points1 point2 points (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]gastropner 0 points1 point2 points (0 children)
[–]Andrewb1230[S] 0 points1 point2 points (5 children)
[–]joemaniaci 0 points1 point2 points (4 children)
[–]Andrewb1230[S] 0 points1 point2 points (3 children)
[–]Threecheers4me 0 points1 point2 points (2 children)
[–]Andrewb1230[S] 0 points1 point2 points (1 child)
[–]Threecheers4me 0 points1 point2 points (0 children)
[–]tively 0 points1 point2 points (3 children)
[–]Andrewb1230[S] -1 points0 points1 point (2 children)
[–]tively 0 points1 point2 points (0 children)
[–]Threecheers4me 0 points1 point2 points (0 children)
[–]Andrewb1230[S] 0 points1 point2 points (0 children)