No output over SSH before waiting for input via scanf() - c

I have a file called get_int.c on a remote Unix system, containing the following:
#include <stdio.h>
int main() {
int input;
printf("Give an integer: ");
fflush(stdout);
scanf("%d", &input);
printf("Try again: ");
scanf("%d", &input);
printf("You said... %d\n", input);
return 0;
}
I have a command to compile and run this file from my local WSL:
sshpass -f pass.txt ssh username#remote.host.address "cd path/to/file/ && gcc get_int.c && a.out"
When I execute this command, I successfully get the prompt Give an integer: and provide one and press enter. Then, however, I do not get the prompt Try again:. I can still type an integer (123) and press enter. When I do, it then prints Try again: You said... 123
As you can see, no printing occurs until I either fflush(stdout) or the program ends. Can I possibly modify my ssh command so that output goes to the local terminal without having to fflush before every scanf?

Output to stdout does not seem to be flushed when reading from stdin on your system in the specific circumstances described. You must flush stdout explicitly with fflush() before every call to scanf():
#include <stdio.h>
int main() {
int input;
printf("Give an integer: ");
fflush(stdout);
scanf("%d", &input);
printf("Try again: ");
fflush(stdout);
scanf("%d", &input);
printf("You said... %d\n", input);
return 0;
}
Alternately, you can set the output stream as unbuffered and won't need to flush it at all:
#include <stdio.h>
int main() {
int input;
setvbuf(stdout, NULL, _IONBF, 0);
printf("Give an integer: ");
scanf("%d", &input);
printf("Try again: ");
scanf("%d", &input);
printf("You said... %d\n", input);
return 0;
}

Related

Windows ping in C with individual IP address input

I'm still relatively new to programming and have decided to create an emergency tool in C as a project for general problems in Windows. In addition I would like to create a menu with different problems, which should be selectable.
Problem one would be e.g. that a server/client cannot be reached. Then a ping and a tracert should be triggered in CMD. But my challenge is that I can't get an individual IP address with every query to be entered. And the result should also displayed. Does somebody has any idea?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define buffer[BUFFER_SIZE] = { 0 };
int main()
{
int selection1;
printf("What is the problem? Type in the appropriate number and press Enter: \n");
printf("1) Something is unavailable.\n");
printf("2) Problem 2\n");
printf("3) Problem 3\n");
printf("4) Problem 4\n");
printf("5) Problem 5\n");
printf("6) Problem 6\n");
printf("7) Problem 7\n");
fflush(stdout);
scanf("%d", &selection1);
if (selection1 == 1)
{
fflush(stdout);
char* pingAdress;
scanf("%c", &pingAdress)
system( "ping %c", pingAdress)
}
Here's an example of how to do your ping use case.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int selection1;
printf("What is the problem? Type in the appropriate number and press Enter: \n");
printf("1) Something is unavailable.\n");
fflush(stdout);
scanf("%d", &selection1);
if (selection1 == 1)
{
fflush(stdout);
char pingAdr[100], pingCmd[100];
printf("Enter host address: ");
scanf("%s", pingAdr);
sprintf(pingCmd, "ping -c 5 %s", pingAdr);
system(pingCmd);
}
return 0;
}

C program not working the way it supposed to work in eclipse [duplicate]

I'm using Eclipse to code in C/C++ and I'm struggling with what might be something pretty easy. In my code below I use printf() and after scanf(). Althougth printf is written before scanf() the output differs. I was able to find out something about similar issue here. But I wasn't able to solve it. Any ideas?
Code:
#include <stdio.h>
int main()
{
int myvariable;
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
Expected output:
Enter a number:1
1
Instead I get:
1
Enter a number:1
Your output is being buffered.
You have 4 options:
explicit flush
fflush after each write to profit from the buffer and still enforce the desiredbehavior/display explicitly.
fflush( stdout );
have the buffer only buffer lines-wise
useful for when you know that it is enough to print only complete lines
setlinebuf(stdout);
disable the buffer
setbuf(stdout, NULL);
disable buffering in your console through what ever options menu it provides
Examples:
Here is your code with option 1:
#include <stdio.h>
int main() {
int myvariable;
printf("Enter a number:");
fflush( stdout );
scanf("%d", &myvariable);
printf("%d", myvariable);
fflush( stdout );
return 0;
}
Here is 2:
#include <stdio.h>
int main() {
int myvariable;
setlinebuf(stdout);
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
and 3:
#include <stdio.h>
int main() {
int myvariable;
setbuf(stdout, NULL);
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
Ok, so finally I used something similar to what #zsawyer wrote as an option labelled 3.
In my code I inserted this line:
setvbuf(stdout, NULL, _IONBF, 0);
As a first line in main():
#include <stdio.h>
int main()
{
setvbuf(stdout, NULL, _IONBF, 0);
int myvariable;
printf("Enter a number:");
scanf("%d", &myvariable);
printf("%d", myvariable);
return 0;
}
I got it from here.

File Handling Error in C

I am learning file handling in C.I have this code but it is not accepting string as an input to write it to a file.Any help will be appreciated.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main(void)
{
FILE * fp1;
fp1 = fopen("abc.txt","a+");
if(fp1==NULL)
{printf("An error occurred");
}
printf("Delete file?\n");
int a,c;
char name [20];
int flag=1;
int ch=1;
while(flag!=0)
{
printf("Enter id input \n");
scanf("%d",&a);
fprintf(fp1,"\n%d\t",a);
printf("Enter Name");
gets(name);
fputs(name, fp1);
printf("Enter No \n");
scanf("%d",&c);
fprintf(fp1,"\t%d\t",c);
printf("Write more then press 0 else 1");
scanf("%d",&ch);
if(ch==1)
{
flag=0;
}
}
fclose(fp1);
}
On running this code the code does not take an input after Enter Name and directly skips to Enter No.I want the output to be in a tabular form.
Use a getchar() after entering id because the \n of 1st scanf stays in buffer.
printf("Enter id input \n");
scanf("%d",&a);
getchar();
When you enter a number for scanf("%d",&a);, you type in a number and press the Enter key. The scanf consumes the number and leaves the newline character ('\n') in the standard input stream (stdin). When the execution of the program reaches gets(name);, gets sees the newline character and consumes it, storing it in name.
Firstly, never use gets as it is dangerous as it doesn't prevent buffer overflows. Use fgets instead:
fgets(name, sizeof(name), stdin);
Secondly, you have to get rid of the newline character. You can do this by flushing the stdin. Or you can simply scan and discard the newline character just after reading the number from scanf by changing
scanf("%d",&a);
to
scanf("%d%*c",&a);
%*c scans and discards a character.
gets() is deprecated, don't use it. you can still use scanf()...
as for the tabulation...think it through.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
FILE* fp1;
fp1 = fopen("abc.txt", "a+");
if (fp1 == NULL) {
printf("An error occurred");
}
int a, c;
char name [20];
int flag = 1;
int ch = 1;
while (flag != 0) {
printf("Enter id input:\n");
scanf("%d", &a);
fprintf(fp1, "%d\t", a);
printf("Enter Name:\n");
scanf("%s", name);
fprintf(fp1, "%s\t", name);
printf("Enter No:\n");
scanf("%d", &c);
fprintf(fp1, "%d\n", c);
printf("Again (0) or Exit(1) ?:\n");
scanf("%d", &ch);
if (ch == 1) {
flag = 0;
}
}
fclose(fp1);
return 0;
}

scanf() to get in the string on the second time

What is wrong with the scanf() to get in the string on the second time, I can't input my string on the second time.
I am not sure with the error that occurs, I can't get this program function well
#include <stdio.h>
#include <stdlib.h>
int main()
{
//variables decleration
char staff_name1[31];
char staff_name2[31];
float sales1, sales2;
//input
printf("Enter staff name\t> ");
scanf("%[^\n]s", staff_name1);
printf("Enter sales amount\t> ");
scanf("%f", &sales1);
printf("\nEnter staff name \t> ");//ERROR,CAN'T INPUT MY STRING
fflush(stdin);
scanf("%[^\n]s", staff_name2);
printf("\nEnter sales amount\t> ");
scanf("%f", &sales2);
printf("\n");
//output
printf("Staff Name\t\t\t\tSales Amount\n");
printf("===================\t\t=============\n");
printf("%-20s \t%12.2f\n", staff_name1, sales1);
printf("%-20s \t%12.2f\n", staff_name2, sales2);
}
my output of this code is as below:
warning: this program uses gets(), which is unsafe.
Enter staff name > kh s
Enter sales amount > 134.14
Enter staff name >
Enter sales amount > 141243.14
Staff Name Sales Amount
=================== =============
kh s 134.14
141243.14
I can't input the second staff name. Can anyone please help me solve this??
fflush(stdin);
is undefined behaviour in standard C. To flush the newline character, you could simply use getchar() instead.
printf("\nEnter staff name \t> ");
getchar();
scanf("%[^\n]s", staff_name2);
I would also use fgets() instead of scanf to read a line and trim the newline if necessary, which offers better control over invalid inputs being entered by user and against buffer overflows.
You have three problems.
I see that you use %[^\n]s. It is wrong. The s isn't part of the %[ specifier. So use %[^\n] instead of %[^\n]s
After you enter the value for sales1, you press Enter. This character stays in the stdin(standard input stream). And when the next character for %[^\n] is \n, it will fail. Fix this problem by adding a space before %[^\n].
Using fflush on stdin invokes Undefined Behavior as per the C11 standard, although the behavior is well defined in some implementations. It is better to remove it so that your code will be more portable.
Additional notes:
You can limit the amount of characters to be scanned so that you can avoid buffer overflows.
You can check the return value of scanf to make sure it is successful. All the scanf in your program will return 1 on success.
Fixed Program:
#include <stdio.h>
#include <stdlib.h> //Unused header
int main()
{
char staff_name1[31];
char staff_name2[31];
float sales1, sales2;
printf("Enter staff name\t> ");
if(scanf(" %30[^\n]", staff_name1) != 1)
{
printf("Could not scan staff_name1");
return -1; //Exit main with a return value of -1
}
printf("Enter sales amount\t> ");
if(scanf("%f", &sales1) != 1)
{
printf("Could not scan sales1");
return -1; //Exit main with a return value of -1
}
printf("\nEnter staff name \t> ");
//fflush(stdin); UB!
if(scanf(" %30[^\n]", staff_name2) != 1)
{
printf("Could not scan staff_name2");
return -1; //Exit main with a return value of -1
}
printf("\nEnter sales amount\t> ");
if(scanf("%f", &sales2) != 1)
{
printf("Could not scan sales2");
return -1; //Exit main with a return value of -1
}
printf("\n");
//output
printf("Staff Name\t\t\t\tSales Amount\n");
printf("===================\t\t=============\n");
printf("%-20s \t%12.2f\n", staff_name1, sales1);
printf("%-20s \t%12.2f\n", staff_name2, sales2);
}

different behavior xcode and Dev-C++

Just beginning to learn C.
if I compile the following code in Dev-C++ the program runs fine.
If I compile in Xcode 3.2.6 it looks like in the screenshot.
I tried different compiler settings in Xcode but the behavior is still the same.
Any ideas on this?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char artist[30];
char album[30];
int tracks;
char albumsingle;
float price;
printf("Please enter CD informations below. \n \n");
printf("enter cd artist: ");
scanf("%[^\n]", artist);
printf("enter cd title: ");
fflush(stdin);
scanf("%[^\n]", album);
printf("enter no. of tracks: ");
fflush(stdin);
scanf("%d", &tracks);
printf("enter a for album s for single: ");
fflush(stdin);
scanf("%c", &albumsingle);
printf("enter price: ");
fflush(stdin);
scanf("%f", &price);
printf("\n\n\nartist: %s\n", artist);
printf("album: %s\n", album);
printf("track no.: %d\n", tracks);
if (albumsingle == 'a'){
printf("cd type: album\n");
} else {
printf("cd type: single\n");
}
printf("price: %.2f EUR\n\n", price);
system("PAUSE");
return 0;
}
My guess is it has to do with the system("PAUSE"); statement. Xcode is used on OSX, which is a UNIX variant, and doesn't have the command pause.
Instead why not just ask the user to press the enter key manually instead? Like this:
printf("Press the ENTER key to continue.\n");
int c;
do
{
c = fgetc(stdin);
} while (c != '\n' && c != EOF);
It has the advantage of working on most systems.
fflush(stdin);
Causes an Undefined Behavior, and hence your program shows different behavior on different compilers.
Reference C standard:
int fflush(FILE *ostream);
ostream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
PAUSE is a Windows, not a Unix command ... so that won't work on the Mac. Use something like getchar() instead if you just want to pause the program at the end.
Include a header file Conio.h and use getch() function whenever you want to hold screen.

Resources