extract from string and put into a file

Hi all,

I'm learning C++, and I got a problem. I found a code in cplusplus, that extract part of the string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
void extract(char *s,char *t,char *d,int pos,int len)
{
s=s+(pos-1);
t=s+len;

while(s!=t)
{
*d=*s;
s++;
d++;
}
*d='\0';

}

I want to put what I extracted into a textfile. I tried, but the text file awlays blank. Please help me. Thank you all.
That's a poorly written C function. If you're really learning C++, you should do it this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
std::string extract(const std::string src, int pos, int len)
{
    return src.substr(pos, len);
}
int main()
{
    std::cout << extract("Hello, world", 3, 2) << '\n';
    // or, to a file
    std::ofstream f("test.out");
    f << extract("Hello, world", 2, 3) << '\n';
}
Last edited on
Thank you so much. I'll try again.
Topic archived. No new replies allowed.