C Program Array more than 1 word [closed] - c

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).

Related

How do i solve this question related to string_Concatenation using C?

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.

scanf() is not working for getting a sentence

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.

Scanf won't notice '\n' char in a program loading only numbers

I have been searching for a few days and I have found only one solution that didn't look perfect to me. Our teacher asked us to create a function that would calculate total lenght of distances in between points provided by user.
My idea was to write code this way, using an array of specific type.
The issue is that, I can't come up with any ideas for how to solve the issue with input: He asked us to make the program end once the user doesn't type anything, so I take it for enter - \n sign.
I could use fgets to get the first variable but:
First, I feel like I don't know any other way beside an array for keeping a long decimal number(in a form of a char array with elements making up the number), that the user could put on the input. I don't know if his script doesn't put some "rofl" number in there.
Second, in this case I think that stripping that array off one X would totally break the total structure of this program. I would rather take both X and Y and accept them as char type, but then the function like atof would probably understand only the X and would stop working after the \n sign.
So Y would be left not given. The accepted input numbers should be of double type. Like:
2 2
3 3
-2 4.5
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
double lenght(struct point *coordinates, int n);
struct point {
double x;
double y;
};
int main()
{
double x,y,TwiceAsBig=3;
int i=0,l=0;
struct point *coordinates;
coordinates = (struct point*)malloc(sizeof(*coordinates)*3);
//allocation of memory for pointtype array with a pointer
while(scanf("%lg %lg",&x,&y)==2)
{
coordinates[i].x=x;
coordinates[i].y=y;
i++;
if(i==TwiceAsBig)
{
coordinates = (struct point*)realloc(coordinates, 2*i*sizeof(*coordinates));
TwiceAsBig=2*TwiceAsBig;
}
}
printf("\n");
for(l;l<i;l++)
{
printf("%lg %lg\n", coordinates[l].x,coordinates[l].y);
}
//checking on the array if the values were loaded correctly
printf("%lg",lenght(coordinates,i));
}
//function for dinstace in between the points
double lenght(struct point*coordinates,int n)
{
int l=0;
for(l;l<n;l++)
{
printf("%lg %lg\n", coordinates[l].x,coordinates[l].y);
}
int pair=0;
double lenght,distance;
for(int AoP;AoP<n-1;AoP++)
{
distance=sqrt(pow(coordinates[pair+1].x-coordinates[pair].x,2)+pow(coordinates[pair+1].y-coordinates[pair].y,2));
pair++;
printf("%lg: ", distance);
lenght=lenght+distance;
}
return lenght;
}
As for your problem, using fgets to read a whole line, and the possibly use sscanf to parse out the two numbers might work.
The problem with using only scanf is that all the numeric format specifiers reads and skips leading white-space automatically, and newline is a white-space character. That means your scanf call in the loop condition will wait until there's some actual non-space characters being input (followed by a newline of course, which leads to the cycle starting over again).
What about using scanf("%[^\n]%*c", test); to read a full string.
Then parsing the result using sscanf?
Something like this:
char* userinput = (char*) malloc(sizeof(char) * 100);
scanf("%[^\n]%*c", userinput);
double a, b;
sscanf(userinput, "%lg %lg", &a, &b);
printf("sum %lg\n", a+b);
With input "-5.5 3.2" the code produces "sum -2.3".
%[^\n]%*c is a "scanset" which tells scanf to read everything excluding '\n' and once it reaches a newline it reads the newline character and disregards it.
You could even use scansets to check the input to some degree by specifying which type of characters you expect to read.
%[0-9 .\\-] // would read digits from 0-9, 'space', '.' and '-'

Combining a string and user input in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm brand new to C, and I was wondering how to combine a string with a user's input. This is what I had, I'm not sure if the user input is correct though.
#include <stdio.h>
int main ()
{
int a;
int input = scanf("%d", &a);
printf ("Hello, \n" + input);
}
But this just asks for input, then prints to the terminal "Hello, ". Does anyone know how to fix this?
&d read digits not characters. You must read characters with %s, because you want got combine a string, like you say, and scanf don't need return integer.
char str[200];
scanf("%s", str);
printf("Hello, %s", str);
In C, scanf returns the count of successfull items matched.
The content of the input is in a.
#include <stdio.h>
int main ()
{
int a;
scanf("%d", &a);
printf ("Hello %d\n", a);
}
First of all, the scanf function does not return the matched value, but the number of values matched. The input value itself is written to the memory location pointed to by the second parameter, in your case, the variable a. See the manual page for scanf (or man 3p scanf) for details.
Second, a more correct printf statement would be something like this:
printf ("Hello, %d\n", a);
where %d in the format string is replaced with the integer a, e.g. if a equals 42, then the statement would have the same effect as printf("Hello, 42\n");. The %d specifier denotes that the respective argument is an integer. See the manual page for printf (or man 3p fprintf) for details.
When you add a C-style string (e.g. "Hello, \n") and an integers (e.g. a) directly using the + operator, there is no integer to string conversion taking place. Instead, the string literal as the first operand is considered as a char const * pointer to which the second operand, integer a, is added to. In which case the format string would point to some strange, which could lead to a crash or security vulnerability. For example, printf("Hello, World!\n" + 7); is equivalent to printf("World!\n"); and only outputs the string "World!\n".
However, "Hello, World!\n" + someLargeInteger will point to some other data in your resulting binary or even outside the binary. This will cause undefined behaviour and might crash your program. Also note that values of type int might be negative.

Printing partial char arrays...with a twist

So I know there are a lot of questions about printing only segments of char arrays in C and I have read them and though my question is similar in nature, there is a small twist to mine. Given my code below, how do I only print out the first four characters of my fmt array? I am not allowed to alter fmt so therefore I must use VAL to specify that I just want to print the value, the new line, and one space.
#define VAL 4
int main() {
char fmt[10] = "%d\n ";
int value = 1;
printf(fmt, value);
}
EDIT:
This is just a fraction of my code because I felt this was all that was necessary. If more is needed I will provide the rest of my code.
EDIT2:
Restrictions:
No new variables & must use VAL to specify how much of the fmt array to be printed.
EDIT3 (FULL QUESTION):
Fill in the missing part of the program, without adding any variable declarations. Ask the user to choose how s/he wants to print the entered integer value. (Look up the integer format specifiers for printf if you don't know them all.) Using the indicated format specifier letter print the integer that was entered earlier, followed by a return, and then reprompt for another format letter (though not for a new integer).
Getting under the complexity limit is a major part of the challenge. Be flexible about which type of loop you choose, and how you read in the format-specifier character. Also, note that scanf skips whitespace when reading a character, if there is a blank before the %c in the format string. And, there is an important use for that VAL define, involving getting rid of spurious blanks in the output. And finally, don't even think about doing this with a big switch or if-else block.
#include <stdio.h>
#define VAL 4 // You might want this
int main() {
char fmt[10] = "%d\n "; // Quickly initializes fmt array
int value;
printf("Enter an integer: ");
scanf("%d", &value);
//from here below is my code, above code is pre-provided
printf("Enter a format specifier (x, X, c, d, i, o, or q to quit): ");
scanf(" %c", &fmt[1]);
while (fmt[1] != 'q') {
printf("%4s", fmt, value);
printf("Enter a format specifier (x, X, c, d, i, o, or q to quit): ");
scanf(" %c", &fmt[1]);
}
}
how do I only print out the first four characters of my fmt array
How about:
printf("%4s", fmt);
It doesn't work because I need the variable value to tell the %d in
fmt what to print out
Options:
Print to a separate string (snprintf) using a length of 4
Process your number until it contains the appropriate number of digits and then print
Adding to cnicutars very good answer, I'd just like to point out that if the array isn't const, you can alter it:
char saved = fmt[4];
fmt[4] = '\0';
printf (fmt, value);
fmt[4] = saved;
Edit
As I specified in my original question, the array cannot be altered.
Yes, well... I misread and thought the original const format string cannot be altered. Nevertheless, I think this tidbid of information can be useful to someone else.
After reading value from input then print could be:
printf("%.*s", VAL, fmt, value);

Resources