Swapping char's in a string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
while(!myFile.eof()){
                                myFile >> code;
                                myFile >> title;
                                myFile >> publisherCode;
                                myFile >> type;
                                myFile >> price;
                                myFile >> paperback;

                                do{
                                size_t loc;
                                loc = title.find('_');
                                if(loc != string::npos)
                                        title.replace(loc, 1, ' ');
                                }while(loc != string::npos);
                                Prog.Add(code, title, publisherCode, type, price, paperback);
                                counter++;
                        }


Using the code above to try and switch all the '_' (Underscore's) in the variable title to a ' ' (blank space's). Im not understanding the correct use I suppose. The error is happening in line 13 in the code above...
The error below is what it gives me.


cs216program2.cpp: In function âint main()â:
cs216program2.cpp:61: error: invalid conversion from âcharâ to âconst char*â
cs216program2.cpp:61: error: initializing argument 3 of âstd::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::replace(typename _Alloc::rebind<_CharT>::other::size_type, typename _Alloc::rebind<_CharT>::other::size_type, const _CharT*) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]â
cs216program2.cpp:62: error: âlocâ was not declared in this scope
Last edited on
line 10: loc should be declare before the loop to be visible at line 14
line 13: use double quotes title.replace(loc, 1, " ");

BTW isn't simpler something like this:
1
2
3
for( unsigned i=0; i<title.length(); i++)
   if ( title[i] == '_')
      title[i] = ' ';
I put in that code and this is what is gave me:


cs216program2.cpp: In function âint main()â:
cs216program2.cpp:57: warning: comparison between signed and unsigned integer expressions


So I tweeked it to:

1
2
3
4
 int size = title.length();
                                for(int i = 0; i < size; i++)
                                        if(title[i] == '_')
                                                title[i] = ' ';


It compiled fine after that. Thanks for the input, I don't know why I was trying to make it so complicated there. :P
Last edited on
that is a warning, not an error.
title.length returns an unsigned type so is best if you compare it with an unsigned type
Last edited on
Topic archived. No new replies allowed.