This question already has answers here:
system function in c is not working for me
(3 answers)
Closed 7 years ago.
I have this C code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
printf("Please enter a number:\n");
scanf("%d",&a);
printf("Your number is: %d\n",a);
system("echo %d",a);
}
I'm interested in the last command, the system() function and why I can't print my variable like i printed it with printf(). I want to be able to ask the user some input , let's say a string and then pass it to the system function.
Practical example:
Ask user for folder name
system("mkdir %s", FolderName);
Thank you in advance! :)
Use snprintf
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
char buf[BUFSIZ];
printf("Please enter a number:\n");
scanf("%d",&a);
printf("Your number is: %d\n",a);
snprintf(buf, sizeof(buf), "echo %d",a);
system(buf);
}
system, unlike printf does not accept multiple parameters, it only accepts one parameter, a const char *command. So you need to build your complete command string first in memory and then pass it to system.
An example would be:
char buf[32];
sprintf(buf, "echo %d", a);
system(buf);
You need to take care not to write more chars into buf than buf has space for. You might want to read the man page for snprintf to rewrite the code in a safer way.
Also: if your code really compiled, then please compile with a higher warning level. At least that would have given you warnings that you are calling system with more parameters than you should.
The System function doesnt have the formatting options like printf, instead the system function takes a C string as a parameter.
Check out the following site for more info.
http://www.tutorialspoint.com/c_standard_library/c_function_system.htm
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 6 months ago.
#include <stdio.h>
int main() {
char v1,v2,v3;
printf("enter: ");
scanf("%c",&v1);
printf("enter: ");
scanf("%c",&v2);
printf("enter: ");
scanf("%c",&v3);
}
this is my sample code and I expect an output like:
enter: a
enter: b
enter: c
but I'm getting output like:
enter: a
enter: enter:
2nd and 3rd print statements are getting executed simultaneously.
The problem is that you're reading characters, so if what you enter is actually aEnterbEntercEnter, that is actually SIX characters, and what you read will be the first 3 (the a, the Enter, and the b)
What you can do is use a space in the scanf format to skip whitespace. If you use scanf(" %c", &v1); then any whitespace (such as Enter) will be skipped, which will cause your result to be what you expect. However, if someone enters something like spaceEnter, the program will seem to hang, waiting for non-whitespace to be entered
The problem lies in buffering. Read this question, which was already mentioned in the comments.
TL,DR: Use scanf(" %c", &v); to read chars, since it ignores all whitespace from the buffer, as well as the trailing newline.
Hello what I would recommend is using a library that allows you to use a function called get_char.
I wrote a program using this function that does what you wanted yours to do.
#include <stdio.h>
#include <string.h>
#include <cs50.h>
int main(void)
{
char v1 = get_char("enter: ");
char v2 = get_char("enter: ");
char v3 = get_char("enter: ");
}
So the program stores 3 char values as they are entered one after another, without all executing at once. I don't know if this is the type of answer that you are looking for or if it will help you, but I figured I would put this out there. If its not really what your looking for let me know!
This is what the terminal looks like btw.:
$ make help
$ ./help
enter: a
enter: b
enter: c
I am learning the language C by myself and with the help of internet.
I came across an exercise, and I was able to read in everything with integers and double, but allowing the user to type in a full sentence and store it in a variable has given me hard time. Can someone explain how I can get a sentence from the user, and store it in a variable. I have tried many things, such as [%^\n] with scanf, and also fget but I am having some trouble. For some reason, it is not working.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int i = 4;
double d = 4.0;
char s[] = "Orange ";
// Declare second integer, double, and String variables.
int secondInt;
double justDouble;
char variable[500];
// Read and save an integer, double, and String to your variables.
scanf("%d", &secondInt);
scanf("%lf", &justDouble);
scanf("%[^ \n]", variable);
// Print the sum of both integer variables on a new line.
printf("%i\n ", i + secondInt);
// Print the sum of the double variables on a new line.
printf("%.1lf\n ", d + justDouble);
// Concatenate and print the String variables on a new line
printf("%s ", s);
printf("%s ", variable);
// The 's' variable above should be printed first.
return 0;
}
This should do the trick by using fgets() in general
#include <stdlib.h>
#include <stdio.h>
int main()
{
// variable to store the message
char msg[100];
// prompting the user to enter the message
printf("Pls enter a msg: ");
// using fgets() to retrieve a whole sentence from the user
fgets(msg, 100, stdin);
// printing the message to stdout
printf("%s", msg);
}
You can learn more about fgets here:
https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm
Let me know if anything is not clear so I can improve my answer
To work with scanf, you need to make sure that everything entered gets read.
In your example, you first expect an integer, and then a double. What does the user type to 'finish' entering the integer? Probably a <RET> (or a blank) - and now you need to scanf these too! Or they will 'clog' the input stream.
For example, your second scanf could be scanf(" %lf"... - note the blank before the % sign, it will read (and discard) any number of whitespace (which is <RET>, <TAB>, <space>).
scanf is very powerful, but needs a lot of detail understanding to be used correctly. Most people don't get it, and therefore claim "it's old and bad and shouldn't be used".
In professional software, it is generally avoided; not because it's not capable, but because the chance is too high that is used wrong, or that it is encountered by a developer that changes it and messes it up.
This question already has answers here:
fgets instructions gets skipped.Why?
(3 answers)
Closed 6 years ago.
I have written a simple program in C which is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int length;
printf("Enter the length of the string:\t");
scanf("%d",&length);
char str1[10];
printf("Enter string:\t");
gets(str1);
printf("%s",str1);
return 0;
}
When I execute it - I get an output as:
Enter the length of the string: 5
Enter string:
Process returned 0 (0x0) execution time : 1.740 s
Press any key to continue.
I don't know why it doesn't ask for the string input and simply quits the program.
When you type '5’ followed by the enter key, you are sending two chars to the program - '5' and newline. So your first scanf gets the '5' and the second gets the newline, which it converts to the number zero.
See How to read a line from the console in C?
When you enter 5 and press enter which is "\n" then "\n" remains in stream and gets assigned to str1. You need to take that "\n" out of the input stream for which many choices are there. You can figure that out. :) Perhaps later I will edit this answer to let you know.
Edit 1:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int length;
char c;
printf("Enter the length of the string:\t");
scanf("%d%c",&length, &c);
char str1[10];
printf("Enter string:\t");
gets(str1);
printf("%s",str1);
return 0;
}
This is incorrect way of doing it but your code will at least start working. You can also simply call getc(stdin) which is slightly better. The scanf regex specified in the other answers where it has been marked as duplicate will also work but is ugly and unnecessarily complicated.
I have not tested this and it may not work.
This question already has answers here:
Disable warning: the `gets' function is dangerous in GCC through header files?
(10 answers)
why gets() is not working?
(4 answers)
Closed 6 years ago.
I'm doing a school project in C where I have to make a function that gets a string input and reverses the string as an output. I could use scanf("%s", answer);, but this only stores the first word of the string. Therefore I decided to go with gets(answer). I know this is unsafe because it doesn't allocate a specific memory size in answer, but I allready did this when defining the array: char answer[100];
I'm not interested in using fgets because the teachers will compile using Cygwin and this warning usually only shows up on Terminal when using a Mac:
warning: this program uses gets(), which is unsafe.
It will display this in the terminal right before prompting the user to type in a string. The other problem I have is that gets(answer) sometimes catches input from the printf("Type a string: ") above it. Is there any way to unvoid this?
Source code:
#include <stdio.h>
#include <string.h>
void reverseString();
int main() {
char str[100];
printf("Type your string here: ");
gets(str); /* Catching return from prinf so add one extra */
gets(str);
reverseString(str);
}
void reverseString(char string[]) {
char temp;
int startChar = 0;
int endChar = strlen(string) - 1;
while (startChar < endChar) {
temp = string[startChar];
string[startChar] = string[endChar];
string[endChar] = temp;
startChar++;
endChar--;
}
printf("\nReverse string is: %s\n", string);
}
Running the code:
warning: this program uses gets(), which is unsafe.
Type your string here: hello world
Reverse string is: dlrow olleh
EDIT:
So I tried using fgets(str, sizeof(str), stdin), but it still skips the user input part. I allso defined a buffer size for str like this: #define BUFFER_SIZE 100 and added it to the array, char str[BUFFER_SIZE].
EDIT:
The apaerant reason why fgets(str, sizeof(str), stdin) isn't working, is because it catches the \n from stdin. I might have to flush it in one way or another.
The question as I understand it is to give you a way to read in a string with spaces. However you don't want to use fgets() because of some reason I didn't follow. Here is another way to do so.
scanf ("%[^\n]%*c", str);
I need help on this exercise from C Primer Plus.
Write a program that requests your first name and does the following with it:
Prints it in a field three characters wider than the name
#include<stdio.h>
#include<string.h>
int main()
{
char a[40];
int p,v=0;
printf("Enter your first name: \n");
scanf("%s",a);
p= strlen(a);
v==p+3;
printf("%s",a);
}
I cant figure out how what to use as a modifier for the width
what should I add in between % and s?
the goal of this excercise is to read and grok the manual page for printf(). The reading part could only be done by you and there is no shortcut. The format specifier is the most complex chapter in C-Programing (other would say 'pointer'), and it is very wise to know where look things up (man-page) in need of remembering.
When you are done reading, you should have a little (or big) understanding of the format-specifier %s with all its possibilities.
EDITH: when you are done reading, and there is still a question whether to use "%*.*s" or "%s" or "%-.*s" etc., please come back with an updated question.
Here is one way to do it:
#include<stdio.h>
#include<string.h>
int main()
{
char a[40];
printf("Enter your first name: \n");
scanf("%s",a);
printf("[%-*s]", (int)(3 + strlen(a)), a);
return(0);
}
The printf() function can do it all.
From the question code, it is clear that "%s" as a format string is understood.
A format string of "%*s" allows the caller to place the (space-padded) width to be specified. For example:
printf("%*s", 10, "Hello");
The above will print "Hello" (as expected), in a 10-character frame. Hence, the command above actually prints: " Hello".
To put the spaces on the other side, tell printf() to left-justify the string using:
printf("%-*s", 10, "Hello");
This results in printing: "Hello "