fork(1) download
  1. #include <iostream>
  2. #include <algorithm>
  3.  
  4.  
  5. void insert_blank(char* line, std::size_t line_size, std::size_t pos)
  6. {
  7. std::size_t index = 0;
  8. while (line[index++])
  9. ;
  10.  
  11. if (index + 1 >= line_size || pos >= index) // sanity check
  12. return;
  13.  
  14. while (index != pos)
  15. {
  16. line[index] = line[index - 1];
  17. --index;
  18. }
  19.  
  20. line[index] = ' ';
  21. }
  22.  
  23. std::istream& get(std::istream& is, int& val)
  24. {
  25. // get a number and remove the trailing newline.
  26. return (is >> val).ignore(100, '\n');
  27. }
  28.  
  29. int main()
  30. {
  31. const char* prompt = "Enter a string (or just hit <ENTER> to quit)\n> ";
  32.  
  33. const std::size_t buffer_size = 1024;
  34. char line_buffer[buffer_size];
  35.  
  36. while (std::cout << prompt && std::cin.getline(line_buffer, buffer_size-1) && line_buffer[0])
  37. {
  38. const char* prompt = "Enter the position to insert blank (or negative to quit)\n> ";
  39.  
  40. int position;
  41. while (std::cout << prompt && get(std::cin, position) && position >= 0)
  42. {
  43. insert_blank(line_buffer, buffer_size, position);
  44. std::cout << "modified: \"" << line_buffer << "\"\n";
  45. }
  46.  
  47. }
  48. }
Success #stdin #stdout 0s 3344KB
stdin
abc
2
1
0
6
-1

stdout
Enter a string (or just hit <ENTER> to quit)
> Enter the position to insert blank (or negative to quit)
> modified: "ab c"
Enter the position to insert blank (or negative to quit)
> modified: "a b c"
Enter the position to insert blank (or negative to quit)
> modified: " a b c"
Enter the position to insert blank (or negative to quit)
> modified: " a b c "
Enter the position to insert blank (or negative to quit)
> Enter a string (or just hit <ENTER> to quit)
>