O
O
OccamaRazor2016-09-07 16:39:58
Programming
OccamaRazor, 2016-09-07 16:39:58

Wrong code work, why does "else" always work?

Always after entering data, "else" is triggered, although the file is successfully created and the entered data is entered into it, how to fix it? Maybe the condition is wrong?

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <string.h>

#define FILENM "some.txt"

int main()
{
  FILE* fp = fopen(FILENM, "a");
  puts("What's your name?");
  char name_buf[100];
  fgets(name_buf, 100, stdin);
  puts("What's your birthday?");
  char date_buf[100];
  fgets(date_buf, 100, stdin);
  int name_bytes = fputs(name_buf, fp);
  int bday_bytes = fputs(date_buf, fp);
  if ((name_bytes>0) && (bday_bytes>0)) {
    printf("okay,wrote name and bday to the file %s\n", FILENM);
  }
  else {
    printf("UHHH...You wrong");
  }
  system("pause");
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2016-09-07
@OccamaRazor

Return Value
On success, a non-negative value is returned.
On error, the function returns EOF and sets the error indicator (ferror).
So that's the norm.
Gotta write
if (name_bytes >= 0 && bday_bytes >= 0) {

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question