Guilherme Galdino
Guilherme Galdino

Reputation: 67

How to properly operate with wstrings?

I am learning about wstrings because I want to understand UTF-8 for a project. I made a simple program to test operations using wstrings:

int main()
{
   std::wstring test;
   std::wstring test2;
   std::wstring test3;
   int n;

   getline(std::wcin, test);

   std::wcout << "\n" << test;

   for (n = 0; n < test.size(); n++)
   {
      test[n] += n * n;
      test2[n] = test[n];
   }
   std::wcout << test2 << "\n";

   for (n = 0; n < test2.size(); n++)
   {
    test2[n] -= n * n;
    test3[n] = test[n];
   }
   std::wcout << test3 << "\n";

  return 0;
}

When I execute it I get this error : "string subscript out of range"

It's my first C++ "serious" project and any help is appreciated!

Upvotes: 2

Views: 128

Answers (1)

cigien
cigien

Reputation: 60218

Your test2 string is empty, so when you do:

test2[n] = test[n];

you are indexing at an invalid location, which invokes undefined behavior. This could result in an exception being thrown.

Instead, you can do:

test2.push_back(test[n]);

You have the same issue with test3, which you can fix the same way.


Alternatively, once you read in test, you can initialize test2 and test3 with the appropriate number of elements:

getline(std::wcin, test);

std::wstring test2(test.size());
std::wstring test3(test.size());

and now you can index into these strings without any problems.


Also, for your problem, you don't even need to do any indexing into test2. Once you've modified test, you can simply assign it like this:

for (n = 0; n < test.size(); n++)
{
      test[n] += n * n;
}
std::wstring test2 = test;

and similarly for test3.

Upvotes: 4

Related Questions