#include <iostream>
#include <string>
#include <cstring>
using namespace std;
string empty(string str) {
for (int i = 0;i < str.length();i ) {
if (str[i] == ' ') {
str.insert(str[i], ",");
}
cout << str[i];
}
return st;
}
int main() {
string str;
getline(cin, str);
empty(str);
return 0;
}
I tried string.resize, or in loop i<str.max_size, str.size and str.replace, I tried to add 1 to size or to length but nothing works.
CodePudding user response:
You are getting a runtime error because the 1st parameter of insert()
expects an index but you are passing it a char
instead, and your input string happens to contain a character whose numeric value is larger than the string's length.
After fixing that, you will then run into a new problem with the loop getting stuck running endlessly once an insert occurs. This is because you are inserting the comma character BEFORE the current space character. So each insert pushes the current space character (and subsequent characters) forward 1 position. Then the next loop iteration increments i
skipping the newly inserted comma character but then finds the same space character again, so it inserts again. And again. And again. Endlessly.
To prevent that, you would need to incremement i
by an extra 1 after an insert to skip the space character.
Try this:
void empty(string str) {
for (size_t i = 0; i < str.length(); i) {
if (str[i] == ' ') {
str.insert(i, ",");
i;
}
}
cout << str;
}
CodePudding user response:
the std::string::insert you are using is not suitable for this program because when your if statement gets execute that is :
if (str[i] == ' ') {
str.insert(str[i], ",");
}
first of all syntax is wrong because you should put str.insert(index,',') (here index is the index of char) that is i in this case so even if you put it like this
for (int i = 0;i < str.length();i ) {
if (str[i] == ' ') {
str.insert(i,',');
}
cout << str[i];
}
it will still not work because : space(' ') is not replaced by .insert() function it just adds character(,) before (space) and then there's space again in next iteration that causing it to stuck in infinite loop
What you can do is :
instead of :
str.insert(i,',');
you can do this :
for (int i = 0;i < str.length();i ) {
if (str[i] == ' ') {
str[i] = ',';
}
cout << str[i];
}
Hope this will help