Combining a string and user input in C [closed] - c

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.

Related

What should I pass to isdigit() in order for it to work properly? [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 3 years ago.
Improve this question
I'm really struggling with isdigit();
I need to test for simple numbers, the relevant part of my code looks like this:
printf("Enter a number\n");
scanf("%f", &a);
if (isdigit(a))
printf("That's a number");
doesn't matter what I input, it won't acknowledge it as a number. I saw somewhere an answer to a similar problem, where they said you can only pass the ASCII code to isdigit if you want accurate evaluation (so only 48-57 will work). Instead '2' for example will be interpreted as the 'start of text' I couldn't find any answer on how to get around that though. I don't remember having that problem in cpp.
Any suggestions?
The isdigit function expects a character code and returns true if the character is one of '0' - '9'.
What you are doing by using the %f format specifier is reading in some text which gets interpreted as a floating point and is then parsed to result in the actual value encoded in the system floating point format (probably IEEE754).
You don't want scanf to interpret the values for you. You want to read the text directly. So declare a char array big enough to read your input and use the %s format specifier. This will give you a string. Then inspect each character in the string with isdigit.
isdigit() checks if a single character is a digit or not. You're passing something that's not a single character.
It would be helpful to have a complete code snippet so we could e.g. know the data type of a. Since you've passed %f to scanf(), presumably it's a float?
If so, the scanf() will return 1 if it is able to parse a float out of whatever input it is given. You can use the return value to determine if the input was valid and not have to even use isdigit().
If you want to use isdigit() for some reason, then you should read the input as a string (scanf("%s", ...something that is a char *...)) and then iterate over each character, passing it to isdigit()
The definition for isdigit() is
int isdigit( int ch );
Checks if the given character is one of the 10 decimal digits: 0123456789.
The behavior is undefined if the value of ch is not representable as unsigned char and is not equal to EOF.
Returns:
Non-zero value if the character is a numeric character, zero otherwise.
Since you are passing the input to a float variable it will not work.
#include <stdio.h>
#include <ctype.h>
int main() {
unsigned char c;
printf(">");
scanf(" %c", &c);
if(isdigit(c)){
printf("Is a digit\n");
}
}

Why is scanf always giving me zero for my first input? [closed]

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 4 years ago.
Improve this question
I'm a Java programmer trying to learn C for a class and man, I can't wrap my head around this. There's no reason why this shouldn't work and yet it doesn't. I'm trying to write a simple calculator app, and no matter how I write it, the first number I input (variable a) ends up being 0, but the 2nd one is fine. With 5 + 6 as input, the output is 6. What am I missing?
#include <stdio.h>
int main()
{
long int a, b, c;
char op;
c = 0;
printf("Enter the expression: ");
scanf("%ld %s %ld", &a, &op, &b);
switch(op){
case('+'): c = a+b; break;
case('-'): c = a-b; break;
case('*'): c = a*b; break;
case('/'): c = a/b; break;
default: break;
}
printf("\n%ld", c);
return 0;
}
The scanf function returns the value of the macro EOF if an input failure occurs
before the first conversion (if any) has completed. Otherwise, the function returns the
number of input items assigned, which can be fewer than provided for, or even zero, in
the event of an early matching failure.
So always check if scanf is successful and if the number of items are correctly assigned.
And it is good to know about the conversion specifiers (what follows after % character) and the length modifiers and their meanings in C.
Check out C Committee Draft (N1570) sections 7.21.6.2 The fscanf function and 7.21.6.4 The scanf function and you will get a good idea of how to use scanf.
I am not sure if you are giving 5<space>+<space>6 or 5+6(without spaces) as input. If you are doing the first, then try doing the second one, i.e, number1+number2 without spaces between the characters.
And remove the spaces in the scanf("%ld %s %ld") too.
Hope this helps.

C Program Array more than 1 word [closed]

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

C-variables won't be added [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have started learning C and I want to make an addition program.
I have written the following code:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
int a,b,c;
scanf("Give a,b",&a,&b);
c=a + b;
printf("A+b=",c);
printf("\n\n\n");
return 0;
}
It is supposed to take 2 numbers from the users and show their sum.
However the only output I get after the user writes 2 numbers is A+b=
Any ideas?
You failed to include a format specifier for your integer variable c. Without this printf doesn't know what arguments to expect following the format string, what their types are, or how they are to be printed. Change:
printf("A+b=",c);
to:
printf("A+b=%d",c);
Note that a good compiler with warnings enabled (e.g. gcc -Wall ...) would have pointed out this simple mistake for you at compile-time.
Also your scanf usage is wrong - change:
scanf("Give a,b",&a,&b);
to:
printf("Give a,b");
scanf("%d %d",&a,&b);
You're missing the %d conversion specifier in the printf() call:
printf("a+b=%d\n", c);
Without that, printf() doesn't know it's getting a second argument and won't do anything with it.
Of course, that c could just be a + b, there's no need to store the sum in a separate variable just to print it.
Also, you need specifiers in scanf(), it should be:
scanf("%d %d", &a, &b);
The first argument to scanf() is not a prompt that's printed, it's describing the expected input.
Last, you should check the return value of scanf() to make sure it's 2 before relying on a and b having valid values. I/O can fail, you need to make sure your program does the right thing if that happens.
scanf is a function used to take in input from the user. You are expecting it to print something, ain't you? You need printf instead:
printf("Give a,b\n"); //\n at the end is good
Now, use scanf to scan in the input:
scanf("%d %d",&a,&b);
You are also missing the %d format specifier in the last printf as other answers have mentioned.
scanf() is an input C function (scan with formatting) that uses format specifiers (%datatype ex: %d or %i = int, which is what you want, or %c = char) to store a data entry in given format, provided by the stdin (keyboard buffer) up to and including a null (\0) termination char(in the case of a string);
The Ampersand (&) in C is used to designate/return the memory address (where variable is stored), as opposed to the value of the variable.
scanf("Give a,b",&a,&b);
c=a + b;
printf("A+b=",c);
The issue with above first line of code is that you forgot to include the format specifiers (%d or %i would both work in this case, as I assume you are adding integers and not floats/etc).
Thus the solution to your first problem is an easy one:
scanf("%d %d",&a,&b);
Also, it seems that you are attempting to combine an input and output in one line.
Printf, like scanf, can use format specifiers, or it can contain only a string of characters, and prints to the stdout (console).
What you want to do is include a prompt asking the user for input before storing said input. You add the \n "newline" character at the end to ensure to provide spacing between other outputs and inputs, among many other reasons when you get into char arrays[], aka strings. But for now, this should do the trick:
printf("Give a,b\n");
scanf("%d %d",&a,&b);
Hope this helps both with the current assignment and with general/C programming concepts!

scanf and printf format modifiers

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 "

Resources