I am unable to take two inputs strings simultaneously in C on Ubuntu. It shows the wrong output.
Simple program:
#include <stdio.h>
main()
{
char s1[20],char s2[20],printf("\nEnter job:");
scanf("%[^\n]s",s1);
printf("Enter hobby:");
scanf("%[^\n]s",s2);
}
Output:
Enter job:student
Enter hobby:
student
It does not allow the input of a second string. How can I overcome this bug?
If you want to allow embedded spaces, modify the scanf formats this way:
#include <stdio.h>
int main(void) {
char job[100], hobby[100];
printf("Enter job:");
scanf("%99[^\n]%*c", job);
printf("Enter hobby:");
scanf("%99[^\n]%*c", hobby);
printf("%s,%s", job, hobby);
return 0;
}
But be aware that empty lines will not be accepted by this scanf format. The linefeed will stay in the input stream, the second scanf will fail too and job and/or hobby will have indeterminate contents, letting printf invoke undefined behavior.
Is is much more reliable to use fgets() and strip the '\n'.
#include <stdio.h>
#include <string.h>
int main(void) {
char job[100], hobby[100];
printf("Enter job:");
if (!fgets(job, sizeof job, stdin))
return 1;
job[strcspn(job, "\n")] = '\0';
printf("Enter hobby:");
if (!fgets(hobby, sizeof hobby, stdin))
return 1;
hobby[strcspn(hobby, "\n")] = '\0';
printf("%s,%s", job, hobby);
return 0;
}
Related
I have the following C code:
#include <stdio.h>
int main()
{
char* ptr;
printf("Enter the word: ");
gets(ptr);
printf("The input string is: ");
puts(ptr);
return 0;
}
It compiles and asks for the input, but after I enter the input, it takes a pause and exits. No further commands are executed or displayed. I am unable to understand the problem. Please help.
#include <stdio.h>
int main()
{
char str[100] = "";
printf("Enter the word: ");
fgets(str, sizeof str, stdin);
printf("The input string is: ");
printf("%s", str);
return 0;
}
Try to use fgets(). gets() is dangerous to use because gets() is inherently unsafe, because it copies all input from STDIN to the buffer without checking size. This allows the user to provide a string that is larger than the buffer size, resulting in an overflow condition.
puts is simpler than printf but be aware that the former automatically appends a newline. If that's not what you want, you can fputsyour string to stdout or use printf.
I am getting this error whenever I run my code in visual Studio:
#include <stdio.h>
#include <ctype.h>
int main() {
char username[10];
printf("Enter Username: ");
scanf_s("%[^\n]", &username);
while (isupper(username)) {
if (username == '-') {
printf("Username cannot contain UpperCase Letters");
}
}
}
Error Image
I don't think you can pass whole array to isupper. Also if you don't want to return anything instead of int main() use void main() or just return 0 in the end or when you want to end after your program executed successfully. As for using scan_s or scanf or getline or whatever I won't say anything because its a different matter and your syntax of scanf_s is certainly wrong.
Also following code will not check for any buffer overflow (not a good practice, you will see even though we gave size 20 char array, this code will work even for larger input which is certainly not a good thing). So you can either limit the size of input or better to read an entire line via fgets() (or getline() if available) and parse the string yourself.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(){
char username[20];
printf("Enter Username: ");
// scanf("%[^\n]", username); <--- Instead of this
scanf_s("%20c", username, 20); // <----Try Using this
int i=0;
while (i<strlen(username)) {
if (isupper(username[i])) {
printf("Username cannot contain UpperCase Letters\n");
return 0;
}
i++;
}
return 0;
}
My first guess would be that your while is an endless loop, try to do it like this:
int i;
for(i=0; i<strlen(username);i++){
if(isupper(username[i])){
printf("Username cannot contain UpperCase Letters");
}
}
I am trying to implement DMA for char variable. But I am unable to take input. I tried with all the possible cases I know:
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
But I can't even enter input data for the character variable ptr_name. I want to take input as "string with space" as input value. How to solve this problem?
And then how to print the entered name in the screen?
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
ptr_name = (char*)malloc(name);
printf("Enter name: ");
//gets(ptr_name);
//scanf("%[^\n]", &ptr_name);
//fgets(ptr_name, name, stdin);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
scanf("%d", ...) does not consume the enter so the next scanf() gets an empty string.
you can use getchar() to consume the enter.
Also, you need to allocate additional byte for the zero at the end of the string / string terminator. See the + 1 in malloc().
As for your questions, your commented scanf() had & before argument 2 which isn't expected (char ** vs. char *) but other than that it will allow spaces in strings. puts() will print the entered name, alternatively you can modify the above printf() to print the name, e.g: printf("\n Your name is: %s", ptr_name);
Lastly, please consult Specifying the maximum string length to scanf dynamically in C (like "%*s" in printf) for dynamically limiting the input size, avoiding buffer overflow.
DISCLAIMER: The following is only "make it work" version of the program above and is not intended for real life use without appropriately checking return codes and limiting the input size:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int name, i;
printf("Enter number of characters for Name: ");
scanf("%d",&name);
getchar();
ptr_name = (char*)malloc(name + 1);
printf("Enter name: ");
scanf("%[^\n]", ptr_name);
printf("\n Your name is: ");
puts(ptr_name);
free(ptr_name);
return 0;
}
if you want to get input with spaces you need to use getline():
getline(&buffer,&size,stdin);
here an example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* ptr_name;
int len;
printf("Enter number of characters for Name: ");
scanf("%d",&len);
ptr_name = (char*)malloc(len);
printf("Enter name: ");
getline(&ptr_name, &len, stdin);
printf("\n Your name is: %s", ptr_name);
free(ptr_name);
return 0;
}
This question already has answers here:
Reading string from input with space character? [duplicate]
(13 answers)
Closed 4 years ago.
I have a simple C program as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[100],b[100];
char *ret;
printf("Enter the string\n");
scanf("%s",a);
printf("Enter the substring to be searched\n");
scanf("%s",b);
ret= strstr(a,b);
if(ret==NULL)
{
printf("Substring not found\n");
}
else
{
printf("Substring found \n");
}
}
When I execute the following program, scanf to read the string into b is not waiting for me to enter the substring and the print statement that prints the substring not found is being printed on the console. I tried to give %sand tried in the scanf statement and removed \n from the printf statements and nothing changed the way it executed the program. It would be great if someone solves this simple problem. Thanks in advance.
You can use scanf ("%[^\n]%*c", variable); with this scanf will read the whole line, instead of stopping when a space is reached.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[100];
char b[100];
char *ret;
printf("Enter the string\n");
scanf ("%[^\n]%*c", a);
printf("Enter the substring to be searched\n");
scanf ("%[^\n]%*c", b);
ret= strstr(a,b);
if(ret==NULL)
{
printf("Substring not found\n");
}
else
{
printf("Substring found \n");
}
}
Also you can use fgets
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char a[100];
char b[100];
char *ret;
printf("Enter the string\n");
fgets(a,100,stdin);//100 is the size of the string, you could use sizeof()
printf("Enter the substring to be searched\n");
fgets(b,100,stdin);//100 is the size of the string, you could use sizeof()
ret= strstr(a,b);
if(ret==NULL)
{
printf("Substring not found\n");
}
else
{
printf("Substring found \n");
}
}
try to use fgets instead of scanf, probably the reason is that the spaces are treated as delimiters, and the parts before the space are treated as a and the part right after the space will be treated as b. Therefore the programme did not prompt you for another input.
For your information: Reading string from input with space character?
Dear fellow Stackoverflowers,
How do you handle for 0 user input?
For example, if the user enters " " or just presses ENTER, how do you handle for that?
#include <stdio.h>
#include <string.h>
int main() {
printf("> \n");
char string[129];
int i = 0, length = 0, flag = 0;
printf("Input a string: ");
scanf("%128s", string);
if(strlen(string) != 0) {
printf("%s\n", string);
} else {
printf("Please enter at least one argument.");
}
}
Quoting C11, chapter ยง7.21.6.2, fscanf(), regarding the %s conversion specifier,
s Matches a sequence of non-white-space characters.
and regarding the steps for execution of a conversion specifier
Input white-space characters (as specified by the isspace function) are skipped, unless
the specification includes a [, c, or n specifier.
So, unless a non-whitespace character is there in the input stream, it will wait. No matching will take place.
Also, it's very important that you check the return value of scanf() and family to ensure that the scanning is success.
That said, int main() should be int main(void) at least to conform to the standards.
Achieving this with scanf() is probably impossible and I have no interest in finding out whether it's possible because this solution
#include <stdio.h> /* For fgets(), fprintf() and printf() */
#include <stdlib.h> /* For EXIT_FAILURE */
#include <ctype.h> /* For isspace() */
int
please_enter_at_least_one_argument()
{
fprintf(stderr, "Please enter at least one argument\n");
return EXIT_FAILURE;
}
int
main(void)
{
char string[130];
printf("> \n");
printf("Input a string: ");
if (fgets(string, sizeof(string), stdin) == NULL)
return please_enter_at_least_one_argument();
else
{
char *pointer;
pointer = string;
while (isspace((unsigned char) *pointer) != 0)
pointer++;
if (*pointer == '\0')
return please_enter_at_least_one_argument();
printf("%s\n", string);
}
return 0;
}
solves the problem and is simple very easy to understand.
Please note that the first please_enter_at_least_one_argument() might not be correct because fgets() might return NULL if you press Ctrl+D (Or on windows Ctrl+Z) and also when an error occurs. But to find out how to handle that you should probably read man fgets(3).