Windows ping in C with individual IP address input - c

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;
}

Related

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

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;
}

Prompt error when user enters a char instead of an expected int

I'm making a menu that lists options 1-3. The user is expected to enter an integer.
scanf("%d", &select_option)
How do I prompt error when user enters a char (for example "a", or "asd" for long strings, or a mixture like "1a2") instead of an expected int? Thanks.
Note: When the user enters a 'char' like 'a', 'asd', the code goes into an infinite loop for some reason.
Here's my program (minimal example):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
while(select_option != 4)
{
switch(select_option)
{
case 1:
printf("You like tennis! Nice! \n");
break;
case 2:
printf("You like badminton! Nice!");
break;
case 3:
printf("You like basketball! Nice!");
break;
default:
system("clear");
printf("Invalid option. Please re-enter your choice (1-4).\n");
}//end switch
printf("Favourite sports? \n");
printf("1. Tennis\n");
printf("2. Badminton\n");
printf("3. Basketball\n");
printf("4. Exit program.\n");
printf("Enter your choice (1-4): ");
scanf("%d", &select_option);
}//end while
}//end main
You could do this:
#include <stdio.h>
int main(void) {
int v;
int ret = scanf("%d", &v);
if(ret == 1)
printf("OK, %d\n", v);
else
printf("Something went wrong!\n");
return 0;
}
where I took advantage of the return value of scanf(), and based on that value, I made an assumption. This will fail for the case of "1a2", but will succeed for "12" and "a".
However, this is a broad question and personally the way I would go for it is:
Use fgets() to read input.
Discard newline.
Convert string to integer (with strtol() for example).
Validate input.
I am assuming u are a beginner. You can use Switch Case which is used usually for creating menus and depending on the choice of the user executes the particular case.
I will show u a small example.
#include<stdio.h>
#include<conio.h>
int main()
{
int n;
printf("Select the sports u want to do\n");
printf("1.Tennis\n2.Karate\n3.Football\n");
scanf("%d",&n);
Switch(n)
{
case 1:printf("You chose Tennis\n");
break; //To prevent from all cases being executed we use
//break which helps from coming out of a loop
case 2:printf("You chose Karate\n");
break;
case 3:printf("You chose Football\n");
break;
default:printf("Please enter an appropriate number !");
//Cases which dont match with the input are handled by default !
}
}
Also to make the user enter input until he wants to exit add a while loop with a variable !
I hope this helps!

Parameters not passing correctly back to main

Source outline: User selects option either to 1. Make Bugatti; 2. Create Bugatti; or 3. Exit program. After each option is complete, the user should be returned back to the menu to select another option.
(Note: the user cannot display the car until it is created, hence the if statement in case 2)
The problem: User's inputs for createCar() function are not being returned back into main() (specifically to case 2 - Display Bugatti) and is displaying some large, odd values, instead of the user's inputs. I know it has something to do with the values not being stored into memory/called back to main().
Also, the while statements in createCar() function are completely being disregarded when I use parameters for some reason.
I would appreciate answers in code to make things easier to resolve personally if possible, thanks!
#include <stdio.h>
#include <math.h>
#define now 2017
//Function headers
void printMenu(void);
void createCar(int *speed, int *year, int *bhp, int *age);
int main(void)
{
//Variables
int userInput;
int topSpeed, yearMade, horsepower, carAge;
/***Loop program to return to menu after option is completed***/
for(;;)
{
//Print menu and get input from user
printMenu();
scanf("%i", &userInput), fflush(stdin);
//Validate input
while(userInput < 1 || userInput > 3)
{
printf("\nWrong input, please retry...\n");
scanf("%i", &userInput), fflush(stdin);
}
//Make decisions after user's choice
switch(userInput)
{
//Option 1: Create car then return to menu
case 1:
createCar(&topSpeed, &yearMade, &horsepower, &carAge);
continue;
//Option 2: Read car details (if created) then return to menu
case 2:
if(topSpeed == NULL)
{
printf("\nYou must first create a car, please retry...\n\n");
continue;
}
printf("\n----Bugatti Veyron----\n");
printf("Top Speed: %i km/h\nYear made: %i\nAge: %i years old\nHorsepower: %i bhp\n", &topSpeed, &yearMade, &horsepower, &carAge);
printf("----------------------\n");
continue;
//Option 3: Kill program
case 3:
exit(1);
}
}
return 0;
}
//Function: Display menu
void printMenu(void)
{
printf("-----------------------------------------\n");
printf("[Bob's Custom Car Creation Complex v1.0]\n");
printf("1. Create Bugatti\n2. Display Bugatti\n3. Exit\n");
printf("-----------------------------------------\n");
}
//Function: Make a car + validate inputs
void createCar(int *speed, int *year, int *bhp, int *age)
{
//Prompt user for top speed + validate input
printf("Enter the top speed of your Bugatti:");
scanf("%i", &speed), fflush(stdin);
while(speed <=0)
{
printf("You cannot have a top speed of nothing silly :-D\nPlease retry...\n");
scanf("%i", &speed), fflush(stdin);
}
//Prompt user for year mate + validate input
printf("What year is your Bugatti produced?:");
scanf("%i", &year), fflush(stdin);
while(year <=0)
{
printf("You cannot own a Bugatti that is from the future laddy!!\nPlease retry...\n");
scanf("%i", &year), fflush(stdin);
}
//Calculate age of car
age = now - year;
//Prompt user for horsepower + validate input
printf("How much horsepower does your Bugatti have?:");
scanf("%i", &bhp), fflush(stdin);
while(bhp <=0)
{
printf("A Bugatti with no engine... doesn't sound too promising :-O\nPlease retry...\n");
scanf("%i", &bhp), fflush(stdin);
}
}
You have to dereference the age and year pointer to get/set its value.
//Calculate age of car
*age = now - *year;
You have to remove the '&' at the scanf() in createVar, because speed, year and bhp are already pointers to int.
Enabling compiler warnings and resolving them would avoid you troubles!

Creating a Menu with c

I am trying to create a menu and my menu is listed a-d. I want the if statement to read a for first item in menu all the way to do but my program keeps crashing. How can I fix this?
#include <stdio.h>
#include <string.h>
int main()
{
char option[4];
system("cls");
printf("+++++++++++++++++++++++++++++++++++++>>>ATHLETE DATA MANAGEMENT SYSTEM<<<++++++++++++++++++++++++++++++++++++++\n\n");
printf("\t\t\t\t\ta\. Enter Athlete Data\n");
printf("\t\t\t\t\tb\. Determine Distance to Reach World Record\n");
printf("\t\t\t\t\tc\. Display Athlete Management Report\n");
printf("\t\t\t\t\td\. Exit\n");
printf("Type the corresponding letter (a-d) to access the menu. ");
scanf("%d", &option);
if(strcmp(option, "a")==0){
printf("Welcome to Athlete Data Page\n");
}
else if(strcmp(option,"b")==0){
printf("Determine Distance to Reach World Record\n");
}else if(strcmp(option, "c")==0){
printf("Athlete Management Report");
}else if (strcmp(option, "d")==0){
printf("Exit Menu");
printf("Press Y for yes and N for no");
}
else{
printf("Incorrect code entered.");
}
return 0;
}
You are using a C-style string variable (an array of characters) char option[4];, but reading it as a decimal integer using the %d in scanf. You would want the %s option to do that.
http://www.tutorialspoint.com/c_standard_library/c_function_scanf.htm

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