fork(8) download
  1. #include <iostream>
  2. #include <fstream>
  3. #include <sstream>
  4. #include <string>
  5. #include <vector>
  6.  
  7. int main()
  8. {
  9. // in your case you'll have a file
  10. // std::ifstream ifile("input.txt");
  11. std::stringstream ifile("User1, 21, 70\nUser2, 25,68");
  12.  
  13. std::string line; // we read the full line here
  14. while (std::getline(ifile, line)) // read the current line
  15. {
  16. std::istringstream iss{line}; // construct a string stream from line
  17.  
  18. // read the tokens from current line separated by comma
  19. std::vector<std::string> tokens; // here we store the tokens
  20. std::string token; // current token
  21. while (std::getline(iss, token, ','))
  22. {
  23. tokens.push_back(token); // add the token to the vector
  24. }
  25.  
  26. // we can now process the tokens
  27. // first display them
  28. std::cout << "Tokenized line: ";
  29. for (const auto& elem : tokens)
  30. std::cout << "[" << elem << "]";
  31. std::cout << std::endl;
  32.  
  33. // map the tokens into our variables, this applies to your scenario
  34. std::string name = tokens[0]; // first is a string, no need for further processing
  35. int age = std::stoi(tokens[1]); // second is an int, convert it
  36. int height = std::stoi(tokens[2]); // same for third
  37. std::cout << "Processed tokens: " << std::endl;
  38. std::cout << "\t Name: " << name << std::endl;
  39. std::cout << "\t Age: " << age << std::endl;
  40. std::cout << "\t Height: " << height << std::endl;
  41. }
  42. }
Success #stdin #stdout 0s 3236KB
stdin
Standard input is empty
stdout
Tokenized line: [User1][ 21][ 70]
Processed tokens: 
	 Name: User1
	 Age: 21
	 Height: 70
Tokenized line: [User2][ 25][68]
Processed tokens: 
	 Name: User2
	 Age: 25
	 Height: 68