-5

C++ insert 1 letter in position 4 how to do it

I have a string like

EURUSD

How do i make it into EUR/USD

I tried something like

string result;
result = "EURUSD";

result.insert(3,"/");

and it doesnt work.

main.cpp:202:24: error: passing ‘const string {aka const std::basic_string<char>}’ as ‘this’ argument of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::insert(std::basic_string<_CharT, _Traits, _Alloc>::size_type, const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>, std::basic_string<_CharT, _Traits, _Alloc> = std::basic_string<char>, std::basic_string<_CharT, _Traits, _Alloc>::size_type = unsigned int]’ discards qualifiers [-fpermissive]
main.cpp:203:2: error: expected ‘;’ before ‘cout’
razlebe
  • 7,134
  • 6
  • 42
  • 57
Baoky chen
  • 183
  • 7
  • 15
  • http://cplusplus.com/reference/string/string/insert/ – triclosan Jul 26 '12 at 07:04
  • 1
    This is your third post today, asking for the implementation of a super-simple procedure in C++. I am voting to close this as too localized. – jogojapan Jul 26 '12 at 07:04
  • @triclosan, [Why cplusplus.com is bad.](http://jcatki.no-ip.org/fncpp/cplusplus.com) – chris Jul 26 '12 at 07:05
  • 1
    To add on, maybe what you need is a [good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – chris Jul 26 '12 at 07:06
  • @chris: If you're determined to drive people away from cplusplus.com with that link, you should at least make sure it's accurate, otherwise it's a bit hypocritical. The first "It says" link, for example, cplusplus.com no longer says what your link says it says. – Benjamin Lindley Jul 26 '12 at 07:10
  • @BenjaminLindley, Interesting, I didn't notice that, but most of what the page includes I've seen for myself in the past. I guess it hasn't been updated since they changed that one, but there are a lot of valid points on it. I'd personally prefer if the better one could catch on and maybe not so many people would inevitably get the ideas that are common misconceptions. – chris Jul 26 '12 at 07:17

2 Answers2

3

Did you try inserting with string::insert ? Something like:

str.insert(??, '/');
cnicutar
  • 178,505
  • 25
  • 365
  • 392
0

This is the way to go:

#include <string>
#include <iostream>

int main()
{
  std::string my_string("EURUSD");

  // insert '/' after 'EUR'
  my_string.insert(3, 1, '/');

  // print result
  std::cout << my_string << std::endl;

  return 0;
}

Arguments of std::string::insert:

  • 3: Position to insert the character
  • 1: How many times to insert the character
  • '/': The character to be inserted.

See also http://www.cplusplus.com/reference/string/string/insert/ for reference.

sebm
  • 9
  • 1