简体   繁体   中英

Why do I have to do ctrl+z twice to break end of file?

Basically I have a struct

typedef struct {
const char *nome;
const char *apelido;
int numero;
} Aluno;

I want to sort this by numero . For example, Input:

jonhy_james_123

jack_china_111

Output :

jack_china_111

jonhy_james_123

I have sucessfully done this, but instead of one CTRL+Z to break end of file, I somehow need to do it twice.

Here is the full code:

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
#include <string.h>


typedef struct {
const char *nome;
const char *apelido;
int numero;
} Aluno;

Aluno aluno(const char *nome, const char *apelido, int numero)
{
Aluno result;
result.nome = nome;
result.apelido = apelido;
result.numero = numero;
return result;
}

Aluno *Aluno_new (int n)
{
  return (Aluno *) malloc (n * sizeof(Aluno));
}

char *str_dup(const char *s)
{
char *result = (char *) malloc(strlen(s) + 1);
strcpy(result, s);
return result;
}

int aluno_read(Aluno *a)
{
int result = 0;
char nome[50];
char apelido[50];
int numero;
while (scanf("%[^_]_%[^_]_%d\n", nome, apelido, &numero) != EOF) {
  a[result++] = aluno(str_dup(nome), str_dup(apelido), numero);
}

return result;
}

void aluno_write(Aluno *a, int n)
{
printf("%s_%s_%d\n", a[0].nome, a[0].apelido, a[0].numero);
for (int i = 1; i < n; i++) {
    printf("%s_%s_%d\n", a[i].nome, a[i].apelido, a[i].numero);
  }
}


int qsort_cmp_numero(Aluno *x,  Aluno *y)
{
return (x->numero - y->numero);
}

int cmp_B(Aluno *x, Aluno *y)
{
  int result = qsort_cmp_numero(x,y);
  return result;
}


int cmp_final2(const void *p, const void *q)
{
return cmp_B((Aluno *) p, (Aluno *) q);
}

void test_sort()
{
  Aluno *aluno = Aluno_new(100001);
  int n_aluno = aluno_read(aluno);
  qsort(aluno, n_aluno, sizeof(Aluno), cmp_final2);
  aluno_write(aluno, n_aluno);
}

int main()
{
  test_sort();
  return 0;
}

While behavior of Ctrl-Z in Windows has some peculiarities, this is secondary at the moment.

The primary problem is that you placed an \\n character at the end of your scanf format. By doing so you asked scanf to wait for non-empty input after the "primary" portion of the input is complete.

This by itself will easily result "strange" behaviors of your scanf , like "ignoring" Enter key and such.

What is that \\n doing there? Why did you include it in your format string?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM