Frage

I'm printing this:

char aulaIP2[50];
char aula[50];

printf("Enter the name of classroom: ");
fgets(aula, 49, stdin);
if (fgets(aula, sizeof aula, stdin)){
        printf("Enter IP classroom: ");
        fgets(aulaIP2, 49, stdin);
        FILE *file = fopen("aules.text", "w+");
        fprintf(file, "%s:%s", aula, aulaIP2);
        fclose(file);
        getchar();
}

and the output in the file is:

306
:127

and I want:

306:127

Why isn't fprintf able to print that in the same line? I have already tried doing it with two fprintfs but it's the same result.

War es hilfreich?

Lösung

From fgets documentation:

A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.

So when you read in your strings, they actually contain the newline character, which is then printed as part of the string. Instead of using fgets() use scanf() which will read until the first whitespace (and not including):

 scanf( "%50s", aula );

Andere Tipps

According to http://www.cplusplus.com/reference/cstdio/fprintf/ fprintf is able to print in one line. See the example on the bottom of that page.

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

int main(int argc, char** argv)
{
    char* aula = "306";
    char* aulaIP2 = "127";

    FILE* file = fopen("aules.text", "ab+");
    fprintf(file, "%s:%s", aula, aulaIP2);
    fclose(file);

    return 0;
}

When I read aules.text, I see:

306:127

Are aula and aulaIP2 actually strings, or were you trying to write integers instead (%d)?

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top