Reputation: 317
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 fprintf
s but it's the same result.
Upvotes: 0
Views: 3987
Reputation: 9648
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 );
Upvotes: 2
Reputation: 551
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.
Upvotes: 0
Reputation: 4069
#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)?
Upvotes: -1