LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   fgets() problems in C (https://www.linuxquestions.org/questions/programming-9/fgets-problems-in-c-156205/)

AMMullan 03-11-2004 04:09 AM

fgets() problems in C
 
Hey all :D

I'm trying to use fgets in my apps now instead of scanf (so much easier to write to strings when your using spaces in them) but when I use them in pwdDiary (my app i'm working on) it just skips past them to the next function....

If i do something like this in pwdDiary:

Code:

char name[64];
char nameAgain[64];

printf("Enter your name: ");
fgets(name, sizeof(name), stdin);
name[strlen(name)-1] = '\0';

printf("Enter it again: ");
fgets(nameAgain, sizeof(nameAgain), stdin);
nameAgain[strlen(nameAgain)-1] = '\0';

This would skip to the second fgets but if i create a new program and use this it works fine....

Anyone run into this before?

worldmagic 03-11-2004 05:47 AM

That seems strange, nothing wrong with your code here.

If could however look like its skipping the first fgets if the line is longer then the specified read buffer?
like 65spaces+newline ? .. First reads 63 spaces (plus adds a \0), next reads 2 spaces and the newline (plus adds a \0) ??

Maybe your files contains alot of trailing spaces? I nothis that sometimes I get them when Im coding.. Mostly when copy and pasting code over an over again while doing debugging.

Hope you solve it, and let us know =)

jim mcnamara 03-11-2004 10:06 AM

fgets() as you use it is fine, but you need to know that (as worldmagic says) there can be junk like spaces or newlines in the stdin buffer.

If you use fgetc() on stdin you can get around those problems. It reads every character out there, until you tell it to stop. Hack ther code below into something that filters out the crud for you, if that's the problem.


Code:

void get_stdin(char *result, int maxlen){
  int ch=0;
  int chars_we_read=0;
  memset(result,0x00,(size_t)maxlen);
  while(ch=fgetc(stdin)!=EOF && chars_we_read < maxlen){
          *(result+ chars_we_read)=(char)ch;
          chars_we_read++;
          if(ch=='\n') break;
  }
}


AMMullan 03-11-2004 05:23 PM

K I just thrw a getchar() in before the fgets and it worked perfectly - apparently fgets() treats srdin differently to functions like scanf()...

Thanks for the help guys :D

bigearsbilly 03-12-2004 04:39 AM

try using
ddd

to have a look at the problem.

billy


All times are GMT -5. The time now is 11:31 AM.