Error when running my code

Hello folks, I'm very new to C++.
My problem is that when I run my coded below on Xcode, I get a following error.

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string
(lldb)

Any tips or solution as to how to fix this problem?

Thank you in advance.
Last edited on
The problem is that you read characters from phrase that not exist when phrase is shorter than 25 chars.
I guess you want to remove all the whitespace from the input and store it in newString.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
using namespace std;
int main()
{
  string phrase;
  cout << "Enter a short phrase: ";
  //cin.ignore(); why skip first char ??????
  getline(cin, phrase);
  string newString;

  // range loop - see https://www.geeksforgeeks.org/range-based-loop-c/
  for (char ch: phrase)
    if (!isspace(ch))
      newString += ch;

  if (newString.length() < 13)
    cout << "Your phrase without space is : " << newString << endl;
  else
    cout << "Your phrase was too long..." << endl;

    system("pause");
  return 0;
}
Last edited on
Thank you for your reply.
Would there be another way with out using loop?
Also could you explain what you mean by whitespace from the input? I could not find any.
Would there be another way with out using loop?

That's what you did, but it's extreme cumbersome. With checking the length it would be like:
1
2
3
4
if (phrase.size() > 0 && ( !isspace(phrase.at(0))
  newString += phrase.at(0);
if (phrase.size() > 1 && ( !isspace(phrase.at(1))
  newString += phrase.at(1);

Why don't you want loops?
If you haven't learned them it's time. They make life so much easier.
Also could you explain what you mean by whitespace from the input? I could not find any.
white are ' ', '\n' '\r', '\t' ...
That's what isspace is for
Thank you so much for your answer, it all make sense now, will learn loop as soon as I can!
Please DON'T delete your code after you've got the answer to your question. It makes this thread useless as a learning resource for others. It's a selfish abuse of this forum.

Please edit your OP to restore it with the original code.
Topic archived. No new replies allowed.