Papuca
Papuca

Reputation: 1

how to find out if there is a newline or number in c?

I have this assignment where I have to read till the "?" char and then check if it is followed by number and newline, or newline and then the number and than again newline. I checked the first char after the "?"

if (scanf("%c",c)=='\n') ...;

but that only works if the first one is a newline, and when it isn't and i want to read the number instead, it cuts the first digit ... for example, it doesn´t read 133 but only 33 ... how do i do this?

I also tried puting the char back, but that wouldn't work

please help :)

Upvotes: 0

Views: 81

Answers (4)

BLUEPIXY
BLUEPIXY

Reputation: 40155

#include <stdio.h>

int main (void){
    int num;
    scanf("%*[^?]?");//read till the "?"
    while(1==scanf("%d", &num)){
        printf("%d\n", num);
    }
    return 0;
}

DEMO

Upvotes: 0

David C. Rankin
David C. Rankin

Reputation: 84642

One advantage of getline over either fgets (or a distant scanf) is that getline returns the actual number of characters successfully read. This allows a simple check for a newline at the end by using the return to getline. For example:

while (printf ((nchr = getline (&line, &n, stdin)) != -1)
{
    if (line[nchr - 1] = '\n')   /* check whether the last character is newline */
        line[--nchr] = 0;        /* replace the newline with null-termination   */
                                 /* while decrementing nchr to new length       */

Upvotes: 1

user3629249
user3629249

Reputation: 16540

this line: if (scanf("%c",c)=='\n') ...; will NEVER work.  
scanf returns a value that indicates the number of successful parameter conversions. 
suggest: 
// note: 'c' must be defined as int, not char
// for several reasons including:
// 1) getchar returns an int
// 2) on some OSs (dos/windows) '\n' is 2 characters long
// 3) if checking for EOF, EOF is defined as an int
if( '\n' == (c = getchar() ) )
{ // then  found newline
    ... 

Upvotes: 0

Use fgets(3), or better yet, getline(3) (like here) to read the entire line, then parse the line using strtol(3) or sscanf(3) (like here)

Don't forget to carefully read the documentation of every function you are using. Handle the error cases - perhaps using perror then exit to show a meaningful message. Notice that scanf and sscanf return the number of scanned items, and know about %n, and that strtol can set some end pointer.

Remember that on some OSes (e.g. Linux), the terminal is a tty and is often line-buffered by the kernel; so nothing is sent to your program until you press the return key (you could do raw input on a terminal, but that is OS specific; consider also readline on Linux).

Upvotes: 0

Related Questions