How do I read a text file and add new line if value is different to value of next row

I need a code to read in text files and write a new line between lines where the value of the first column is different to the next. Any guidance on my current code would be greatly appreciated.

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


int main()
{
	float *doub1, *doub2;
	char *line, *rest, lines, *line2, filename[100], ch;
	FILE * newfile;
	printf("enter file name: ");
	scanf("%s", filename);
	newfile = fopen(filename, "r+");
	while (ch = fgetc(newfile) !=EOF)
	{
		if (ch == '\n')
		{
			lines++;
		}
	}
	for (int i = 0; i < lines/2; i++)
	{
		fgets(line, 100, newfile);
		sscanf(line, "%e %s", doub1, rest);
		fgets(line2, 100, newfile);
		sscanf(line, "%f %s", doub2, rest);
		if (doub2>doub1)
		{
			fputs( "\n", newfile);
		}
		doub2=doub1;
		line2=line;
	}
	return 0;
}
Last edited on
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
# include <iostream>
# include <string>
# include <vector>
# include <fstream>
# include <utility>

int main()
{
	std::ifstream inFile {"C:\\test.txt"};
	std::vector <std::string> originalFile{};
	if(inFile)
    {
        std::string line{};
        while (getline(inFile, line))
        {
            if(inFile)originalFile.push_back(std::move(line));

            if(originalFile.size() >= 2 &&
               originalFile.back() != originalFile[originalFile.size() - 2])
            {
                if(inFile) originalFile.insert(--originalFile.end(), std::string {"non - duplicate"});
                //vector insert is linear complexity in distance b/w insert position & end of container
                // given above std::list may not give much advantage in this case
                //replace std::string {"non-duplicate"} with whatever's required
            }
            line.clear();
         }
    }
    for (const auto& elem : originalFile)std::cout << elem << "\n"  ;;
}
/*Sample file:
hi
this is
this is
hello world
*/
@gunnerfunner,
I am afraid you are wasting your time. He is getting help there already.
https://cboard.cprogramming.com/c-programming/173480-help-reading-text-file-adding-new-lines-depending-value-line.html#post1269515
Topic archived. No new replies allowed.