Hello everyone,

I'm working on a project which I should read from a text file. Text file contains two lines of sequational numbers, something like this:
[TEX]
4 5 2 1 10 8
3 4 6 1
[/TEX]

In the program, I need to find out where exactly a new line begins (after 8 in the example). I've heard of '\n' character but not sure how to use it for this purpose.

I thought something like that:

char num[5];
while(!feof(text))
{
fscanf(text,"%s",%num);
if(

Dani AI

Generated

As guessed, the newline in a text file is the '\n' character, but the C input functions matter: functions in the scanf family (for example fscanf with %s or %d) treat any whitespace (spaces, tabs, newlines) as separators and will not tell you where a line break occurred. To detect "start of a new line" you must either read the file line-by-line (so line boundaries are explicit) or read characters and look for '\n' yourself. Avoid loops like while(!feof(fp)); instead check the return values of fgets, fscanf, or fgetc.

A common and robust approach is to read each line with fgets and then parse the numbers from that line (so each call to fgets corresponds to a new line in the file):

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE *fp = fopen("input.txt","r");
    char buf[512];
    while (fgets(buf, sizeof buf, fp)) {
        // buf contains one whole line (ends with '\n' unless truncated)
        // parse numbers from buf (use strtol/sscanf/strtok as needed)
    }
    fclose(fp);
    return 0;
}

If you must read numbers one by one but still detect line boundaries, read the number then peek ahead for the next non-space character and check whether a '\n' was encountered:

#include <stdio.h>
#include <ctype.h>

int n;
while (fscanf(fp, "%d", &n) == 1) {
    // process n
    int c, saw_nl = 0;
    while ((c = fgetc(fp)) != EOF) {
        if (c == '\n') { saw_nl = 1; break; }
        if (!isspace((unsigned char)c)) { ungetc(c, fp); break; }
    }
    if (saw_nl) { /* new line begins next */ }
}

Extra tips: handle Windows CRLF by tolerating '\r' before '\n'; use strtol for safer number parsing; use getline (POSIX) if lines can be arbitrarily long; check all return values; and use ftell if a byte offset is required. 's brief reply didn't add detail—these patterns are the reliable ways to detect line boundaries in C.

glad we could help?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.