fork download
  1. #include <string>
  2. #include <vector>
  3. #include <iostream>
  4. #include <sstream>
  5.  
  6. int main()
  7. {
  8. std::vector<int> numbers;
  9. std::string line;
  10.  
  11. // ifstream myfile ("example.dat");
  12. std::istringstream myfile(
  13. "3\n"
  14. "12\n"
  15. "23\n"
  16. "34\n"
  17. "12 34\n"
  18. "12 12\n"
  19. "34 23\n"
  20. "23 23\n\n"
  21. );
  22.  
  23. while ( std::getline(myfile, line) )
  24. {
  25. try {
  26. int num = std::stoi(line) ;
  27. std::cout << "Converted \"" << line << "\" to " << num << '\n' ;
  28. }
  29. catch( std::exception& ex)
  30. {
  31. std::cout << "ERROR: " << ex.what() << '\n' ;
  32. std::cout << "\tUnable to convert \"" << line << "\" to a number.\n" ;
  33. }
  34. }
  35. }
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
Converted "3" to 3
Converted "12" to 12
Converted "23" to 23
Converted "34" to 34
Converted "12 34" to 12
Converted "12 12" to 12
Converted "34 23" to 34
Converted "23 23" to 23
ERROR: stoi
	Unable to convert "" to a number.