Modify a string

Hi,
i have a file like this (akagi.txt):

0.000 0.175 4 L
0.394 0.404 1 R
0.450 0.500 5 L short
0.707 0.747 1 L
0.772 0.822 5 R
0.867 0.917 5 R short

i read it with getline an put each line into "nota" string (see code)
how can i change for example all the 5 R in 4 R?

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
  #include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string nota;

    ifstream leggi("akagi.txt");

            if (leggi)
            {
                while (!leggi.eof())                            
                {
                    getline(leggi, nota);

                    if (nota.compare(12,3,"5 L") == 0)
                        cout << "trovato" << endl;
                }
            }

    leggi.close();                                             

    return 0;
}


thank you
Last edited on
Hi,
i'm very new in c++

I tryed to modify the "if......." (if (nota.compare(12,3,"5 L") == 0) cout << "trovato" << endl;)
but got error:
terminate called after throwing an instance of 'out of range'
what <> : basic string::compare
Last edited on
@il dottore

Here's one way to do it.

Instead of hard-coding the check, you could first ask the user what number and letter to check for, and then what to change them into.
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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
 string nota;

 ifstream leggi("akagi.txt");

 if (leggi)
 {
	while (!leggi.eof())                            
	{
	 getline(leggi, nota);
	 int len = nota.length();

	 for(int x=0;x< len; x++)
	 { 
		if (nota[x] == '5')
		{
		 if (nota[x+2] == 'R')// used +2 because of the space between the 5 and R
			nota[x] = '4';
		}
	 }                        
	 cout << nota << endl;
	}
 }
 leggi.close();                                             
 return 0;
}
Last edited on
Thank you whitenite1
it works
A more general solution might look something like this:

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
#include <iostream>
#include <fstream>
#include <string>

std::string& replace(std::string& source, const std::string& pattern, const std::string& repl)
{
    auto pos = source.find(pattern);

    if (pos != std::string::npos)
    {
        auto beg = source.begin() + pos;
        auto end = beg + pattern.size();

        source.replace(beg, end, repl);
    }

    return source;
}


int main()
{
    std::ifstream in("akagi.txt");

    const std::string pat("5 R");
    const std::string rep("x x");

    std::string line;
    while (std::getline(in, line))
        std::cout << replace(line, pat, rep) << '\n';
}
Topic archived. No new replies allowed.