Having trouble with inserting into String

Feb 17, 2011 at 8:13pm
I am having trouble getting this function to work right. I would like it to search the string looking for quotations marks and insert a '\' right before the quotation. I have also tried using the string::find() function but it didn't work correctly either. Is there a better way? I am open to suggestions. Thank you.

testfile.txt
1
2
This" is a s"ample quo"tation sentence.
Thi"s is another "sample sentenc"e.



//start code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <Windows.h>
using namespace std;


void find_quotes(string& this_phrase)
{
	cout<<"\n"<<this_phrase<<endl;
	int phrase_length=this_phrase.length();
	
	for(int x=0; x<phrase_length;x++)
	{
		if(this_phrase[x]=='"')
		{
			this_phrase.insert(x,"\\");
			cout<<this_phrase[x];
			//Sleep(100);
		}
		x++;
	}
	
	cout<<"\n"<<this_phrase;

	cin.get();
}

int main()
{
    fstream my_inf;
    string temp_string;

    my_inf.open("testfile.txt", ios::in);

    while(!my_inf.eof())
	{
		temp_string=" ";

		if(!my_inf)
		{
			cout<<"ERROR: Input file not found.\n"; break;
		}

		std::getline(my_inf, temp_string,'\n');
                find_quotes(temp_string);
    }


	my_inf.close();

	cout<<"\nProgram Finished";

    cin.get();
    return 0;
}

//end code
Feb 17, 2011 at 10:55pm
Just something I spotted, but why do you have line 41 where it is? Right now it performs that check at every iteration of the while loop, it's not a huge performance hit now but it bothers me a little and it's a bad habit.

EDIT: Got rid of extra white space.
Last edited on Feb 17, 2011 at 10:56pm
Feb 18, 2011 at 3:15am
Thanks Computergeek01, Yeah I will change that, haha. I did not notice that.

Any suggestion about how to fix the code so that it works properly?
Feb 18, 2011 at 6:42am
Dear Smith,

What you have tried is good. but, small logic mistake in your code in find_qoutes().

your code with little changes to obtain your requirement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void find_quotes(string& this_phrase)
{
	cout<<"\n"<<this_phrase<<endl;
	int phrase_length=this_phrase.length();
	
	for(int x=0; x<phrase_length;x++)
	{
		if(this_phrase[x]=='"')
		{
			this_phrase.insert(x++,"\\");  // x should be increment when new character added
			cout<<this_phrase[x];
			//Sleep(100);
		}
             // increment x for every loop is not required here. for will do that
	}  
	cout<<"\n"<<this_phrase;
	cin.get();
}
Feb 18, 2011 at 8:47am
Richardforc,

Wow! Thanks a lot for showing me how to fix my code. I didn't even think about trying that. A++ for the help. I have just got out of CS1 so I still have a lot to learn. Thanks again!

--Clint
Topic archived. No new replies allowed.