How to use strncpy?

The plan is to read the source code of another program, determine where the comments are(anything that has // before it), then replace the whole comment with spaces so that the program will ignore the comments when parsing.

This is what I have so far

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
char line[256];
int x = 0;
char *ptr;
while(!inFile2.eof())
{
    inFile2.getline(line, 256);
    char *pch = strstr(line, "//");
    strncpy(pch, "  ", 3);


    ptr = strtok(line, " ");


    while (ptr != 0)
    {
        cout << ptr << endl;
        ptr = strtok(NULL, " ");
    }


}


Thanks for any help!
Your program will read and parse a text file, assuming some syntax in the context. You want to ignore comments. Is that right?

If a line contains "//", then the "//" and the rest of the line is a comment. Is that right?
(What if a string literal contains //?. Is the // the only allowed comment syntax? It is not for C++.)

Why do you want to "replace with spaces"? Why not simply discard the rest of the line?

Why do you use plain array and C-string functions rather than std::string?

The stream::eof() is not a reliable indicator of the end of the input. Consider
1
2
3
while ( inFile2.getline(...) )
{
  ...



[EDIT] Please, do not doublepost. You did already have a thread http://www.cplusplus.com/forum/beginner/229984/
Last edited on
There is no need to replace comments with spaces. Just terminate your line at the pos of //
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream>
#include<fstream>

using namespace std;

int main()
{
  char line[256];
  ifstream src(__FILE__);
  // a comment that should disappear
  char *ptr;
  while (src.getline(line, sizeof(line)))
  {
    ptr = strstr(line, "//");
    if (ptr != nullptr)
      *ptr = '\0'; // this will remove anything after ptr

    cout << line << "\n";
  }
}
Topic archived. No new replies allowed.