I am new to coding. This is a Question from the #30 days code on Hackerrank.
But, I'm unable to solve it. can anyone help me by telling me what's the problem here?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int i = 4;
double d = 4.0;
char s[] = "Hello ";
// Declare second integer, double, and String variables.
int j;
char *ptr=s;
double c;
char p[100];
// Read and save an integer, double, and String to your variables.
scanf("%d",&j);
scanf("%lf",&c);
scanf("%[^\n]%*c",p);
// Print the sum of both integer variables on a new line.
printf("%d\n",i+j);
printf("%.1lf\n",c+d);
printf("%s%s",s,p);
// Print the sum of the double variables on a new line.
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first
return 0;
}
It is showing the result
Input:
12
4
Output:
16
8.0
Hello o}┌vl
╤
As you can see I want to print concatenated string but it wouldn't even allow me to input the data into the string.
I guess you press the Enter key for all input?
That Enter key will be added as a newline in the input buffer.
The %[^\n] format stops reading once it find a newline. And the first character it reads is a newline. So it doesn't read anything, and the array p will remain uninitialized with indeterminate contents.
You need to tell scanf to skip the leading newline, which is done by adding an explicit space in the format string:
scanf(" %99[^\n]",p);
// ^
// Note space here
Note that I limit the input to 99 characters, which will not overflow the buffer. And also note that you don't need to read the newline after the string.
Related
I was trying to input a string of characters and only output the last and the first character respectively. Below is the code I'm using.
#include<stdio.h>
int main(){
for(int i=0;i<3;i++){
int n; // length of the string
char string[101];
scanf("%d %s", &n, &string);
fflush(stdin); // sometimes I also use getchar();
printf("%c%c", string[n+1], string[0]);
}
printf("\n");
return 0;
}
I'm using for loop because i wanted to input the string 3 times, but when I ran the code the input isn't what I expected. If I input e.g.
5 abcde
output
a //there's space before the a
can you help me tell where I've gone wrong?
input:
5 abcde
6 qwerty
3 ijk
excpeted output:
ea
yq
ki
Few problems in your code:
In this statement
scanf("%d %s", &n, &string);
you don't need to give & operator with string. An array name, when used in an expression, converts to pointer to first element (there are few exceptions to this rule). Also, the size of string array is 101 characters but if you provide input more than 101 characters, the scanf() end up accessing string array beyond its size. You should restrict the scanf() to not to read more than 100 characters in string array when input size is more than that. (keep the remain one character space is for null terminating character that scanf() adds). For this, you can provide width modifier in the format specifier - %100s.
You are not validating the string length input against the input string from user. What happen, if the input string length is greater than or less than the actual length of input string!
fflush(stdin) is undefined behaviour because, as per standard, fflush can only be used with output streams.
I was trying to input a string of characters and only output the last and the first character respectively.
For this, you don't need to take the length of the string as input from user. Use standard library function - strlen(). This will also prevent your program from the problems that can occur due to erroneous length input from user, if that is not validated properly.
Putting these altogether, you can do:
#include <stdio.h>
#include <string.h>
int main (void) {
for (int i = 0; i < 3 ; i++) {
char string[101];
printf ("Enter string:\n");
scanf("%100s", string);
printf("Last character: %c, First character: %c\n", string[strlen(string) - 1], string[0]);
int c;
/*discard the extra characters, if any*/
/*For e.g. if user input is very long this will discard the input beyond 100 characters */
while((c = getchar()) != '\n' && c != EOF)
/* discard the character */;
}
return 0;
}
Note that, scanf(%<width>s, ......) reads up to width or until the first whitespace character, whichever appears first. If you want to include the spaces in input, you can use the appropriate conversion specifier in scanf() or a better alternative is to use fgets() for input from user.
Line 11: string[n+1] -> string[n-1]
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.
I must write a program in C that can print the middle letter of the string you entered. Spaces () are also calculated, and the number of characters must be odd.
Ex. Input
Hi sussie
--> 9 characters, including space
The output should be s.
I have tried this:
#include <stdio.h>
#include<string.h>
char x[100];
int main(void)
{
printf("Hello World\n");
scanf("%c\n",&x);
long int i = (strlen(x)-1)/2;
printf("the middle letter of the word is %c\n",x[i]);
return 0;
}
and the output always shows the first letter of the word I have entered.
You're only reading the first character from stdin (and incorrectly; you shouldn't be using &).
If you must use scanf, you should use this format:
scanf("%99[^\n]", x);
This is safe and doesn't read past the buffer.
Note that %s wouldn't work here. %s causes scanf to interpret whitespace as the end of the string.
A much better, safer, and easier solution would be to use fgets instead of scanf; fgets is safer and it doesn't require you to change a format string when you change the size of your array:
fgets(x, sizeof(x)-1, stdin);
This eliminates any possible issues with whitespace or buffer overflow.
int main()
{
char arr[1024];
char a;
int i,counter=0;
printf("enter string :: ");
fgets(arr,sizeof(arr),stdin);
for(i=0;i<strlen(arr);i++)
counter++;
for(i=0;i<strlen(arr);i++)
{
if(i==(counter/2))
printf("%c\n",arr[i]);
}
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This question is from HackerRank, I try to use %[^\n]s for a long word. But, the output keep on producing .0
How to replace %[^\n]s to something else for the string to receive the input ?
Here is the input :
12
4.0
is the best place to learn and practice coding!
Here is my output :
16
8.0
HackerRank .0
This is the expected output :
16
8.0
HackerRank is the best place to learn and practice coding!
This is my full code, as you can see, it does not recognize %[^\n]s. How to solve this problem? Thank you.
Full code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main() {
int i = 4;
double d = 4.0;
char s[] = "HackerRank ";
// Declare second niteger, double, and String variables.
int value1, sum1, value2;
double e = 2.0, sum2;
char t[30];
// Read and save an integer, double, and String to your variables.
scanf(" %d", &value1);
scanf("%d", &value2);
scanf("%[^\n]s", t); //** POINT OF INTEREST **
// Print the sum of both integer variables on a new line.
sum1 = value1 + i;
printf("%d\n", sum1);
// Print the sum of the double variables on a new line.
sum2 = d * e;
printf("%.1lf\n", sum2);
// Concatenate and print the String variables on a new line
// The 's' variable above should be printed first.
printf("%s %s", s, t);
return 0;
}
Considering your input-output examples, I amended your code like this:
char t[256]; // the string "is the best place to learn and practice coding!" MUST FIT!!!
...
scanf("%d", &value1);
scanf("%lf", &d); // NOT %d, %lf !!! &d or &e - I don't know - depends on you
scanf("\n%[^\n]", &t);
...
printf("%s%s", s, t); // you don't need a space, since your "s" already contains it.
Works fine for me.
UPD:
Now it actually works fine.
The reason your scanf() is failing to read the string is most likely that there's a newline character still in the stream that wasn't read off after you scanned the last number. "%[^\n]" tries to read a string, containing anything except a newline, and stops when an invalid character is reached; since the next character is a newline, there are no valid characters to read and it fails to assign the field. All you need to do to fix it is read the newline character before you scan the string.
Also, the %[ specifier does not need an s at the end -- it's a different conversion specifier from %s, not a modifier for it.
And finally, it's recommended that you specify the width for %[ or %s so that a long input string won't overrun the buffer you read the string into. The width should be the maximum number of characters to read before the null, so one less than your buffer size.
Using scanf(" %29[^\n]",t) will read off whitespace (including that newline) before scanning the string, and then scan a string with up to 29 non-newline characters (for a 30-char buffer).
I am currently trying to solve a problem from CodeChef but I am having troubles with using fgets() inside a loop.
The first input (T) is going to be a positive integer containing the number of user inputs.
Then delimited by newline characters, the user is going to input a string below the length of 10 under any circumstances.
So, I've tried this:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int T;
int diffX, diffY;
char s[SIZE];
scanf("%d", &T);
while (T--){
fgets(s, SIZE, stdin);
printf("%s\n", s);
}
return 0;
}
However, when I attempted to test the code with the following inputs:
3 Hello Hi What
I was only able to input until "Hi" then the program exited successfully (returning 0).
Why is this the case and how can I fix it?
Thank you in advance,
kpark.
fgets() consumes the newline left behind by the first call to scanf(). So, it is consuming 3 lines, but the first line looks like an empty line to the fgets() loop you have.
You can fix this by using fgets() to get the first line too, and parse the string into a number using sscanf().
fgets(s, SIZE, stdin);
sscanf(s, "%d", &T);
/* ... */
It is counting the read of the T as part of the counting. Add a newline in the scanf.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int main()
{
int T;
int diffX, diffY;
char s[SIZE];
scanf("%d\n", &T);
while (T--){
fgets(s, SIZE, stdin);
printf("%s\n", s);
}
return 0;
}
Is your Question is about how to read Multiple Strings in C ?
Then it can be done by 2 ways :-
1.By declaring two dimensional Array of characters.
//Let say we want 6 strings each of them having max 10 characters.
char set[6][10] ;
for(int i=0;i<6;i++)
scanf("%s",set[i])
2.By declaring one dimensional Array of pointers to character (Notice the naming Conventions), in which each of those pointer pointing to a String.
int main(){
int i,numOfStrings;
char temp[30];
printf("Enter Number of strings in set ");
scanf("%d",&numOfStrings);
//Here We have defined array of pointer that will store each string sepratly.
//Arry of pointer to character.
char *setOfStrings[numOfStrings];
for(i=0;i<numOfStrings;i++)
{
printf("Enter string ");
scanf("%s",temp);
setOfStrings[i]= (char*)malloc(sizeof(temp)); //allocted new memory and gave it to array of pointer
strcpy(setOfStrings[i],temp);
}
for(i=0;i<numOfStrings;i++)
{
printf("string = %s \n",setOfStrings[i]);
}
return 0;
}
But that need to understand :
In case of array of pointers we may initialize them with String but Can't take as input from Command line like
char *set[2]={"Dinesh","Kandpal"}; //Its valid but you can't do this from command line
for doing so What we do we will create an space dynamically ,store that address in the one of the element in 1-D array of pointers and then whatever value we have scanned copy that content to the another string to the location that we created using malloc