as expected this prog. should accept a number until it encounters a 4 but it gives some garbage value. why?
int main(void)
{
int a;
printf("Enter a number: ");
scanf("%[^4]d", &a);
printf("You entered: %d\n", a);
return 0;
}
As far as I know scansets are meant to be used with strings (which makes the d not act as an integer placeholder specification). One way to write it is to read the input into a string and then parse it:
int main(void)
{
int a;
char b[255];
printf("Enter a number: ");
scanf("%254[^4]", &b);
a = atoi(b);
printf("You entered: %d\n", a);
return 0;
}
I'm keeping the modified code to a minimum, you'd definitely need some extra checks for input sanity.
To clarify: The 254 prefix limits the amount of data that scanf will capture, so as to not exceed the size of the buffer (strings are terminated with an extra null character, so the read length must be smaller than the actual size)1.
The scanset working with only characters.
Here is my sample code. (but, I don't know what you really want.)
#include <stdio.h>
int main(void) {
char buffer[128];
printf("Enter a number: ");
scanf("%[^4]s", buffer);
printf("You entered: %s\n", buffer);
return 0;
}
The result is,
Enter a number: 12345678
You entered: 123
Additionally, if you want integer value, use atoi().
Related
When I enter 2, I wish to get this output:
value: 2.4
But when I do the multiplication, I am getting this:
value: 2.400000
This is my code:
#include <stdio.h>
int main()
{
float num;
float result;
printf("Number: ");
scanf("%f", &num);
result = num * 1.2;
printf("Result: %f", result);
}
What can I do?
You can specify how many digits you want to print after the decimal point by using %.Nf where N is the number of digits after the decimal point. In your use case, %.1f: printf("Result: %.1f", result).
There are some other issues in your code. You are making use of scanf(), but you are not checking its return value. This may cause your code to break.
scanf() returns the number of arguments it successfully parsed. If, for any reason, it fails, it doesn't alter the arguments you gave it, and it leaves the input buffer intact. This means whenever you try again and read from the input buffer, it will automatically fail since
it previously failed to parse it, and
it didn't clear it, so it's always there.
This will result in an infinite loop.
To solve the issue, you need to clear the input buffer in case scanf() fails. By clearing the buffer, I mean read and discard everything up until a newline (when you previously pressed Enter) is encountered.
void getfloat(const char *message, float *f)
{
while (true) {
printf("%s: ", message);
int rc = scanf("%f", f);
if (rc == 1 || rc == EOF) break; // Break if the user entered a "valid" float number, or EOF is encountered.
scanf("%*[^\n]"); // Read an discard everything up until a newline is found.
}
}
You can use it in your main like that:
int main(void) // Note the void here when a function doesn't take any arguments
{
float num;
float result;
getfloat("Number", &num);
result = num * 1.2;
printf("Result: %.1f", result); // Print only one digit after the decimal point.
}
Sample output:
Number: x
Number: x12.45
Number: 12.75
Result: 15.3
I am a beginner in C and would like to know what's the problem about my code here :
#include "stdio.h"
int main(void)
{
int a;
printf("Please input an integer value: ");
scanf("%d", &a);
printf("You entered: %d\n", a);
return 0;
}
My problem is that I have to type a value before having any consol output, for example if I type 7, I get this console output : Please input an integer value: You entered: 7
I tried the exact same code in another computer and it worked pretty well, I guess it's a buffer problem ? but I have no idea how to fix it.. Any ideas please ?
As other already mentioned, to guarantee that that line is going to be printed at that point in your code you can flush the standard output like this,
#include "stdio.h"
int main(void)
{
int a;
printf("Please input an integer value: ");
fflush(stdout);
scanf("%d", &a);
printf("You entered: %d\n", a);
return 0;
}
you can read this for more details, Why does printf not flush after the call unless a newline is in the format string?
updated thanks to #Osiris comments
It takes in a word and a number, I can't seem to understand why the number variable won't receive the input, help please.
#include <stdio.h>
int main(void) {
char userWord[20];
int userNum;
scanf("%s", userWord);
printf("%s_", userWord);
scanf("%s", userNum);
printf("%d\n", userNum);
return 0;
}
Should be:
Input: Stop 7
Output: Stop_7
What I get:
Input: Stop 7
Output: Stop_0
Change
scanf("%s", userNum);
to
scanf("%d", &userNum);
You used format %s for reading in an integral value; it should have been %d.
Once having fixed this (i.e. by writing scanf("%d", &userNum);, note that your code will read in a string and a number even if the string and the number were not in the same line (cf., for example, cppreferene/scanf concerning format %s and treatment of white spaces). Further, you will run into undefined behaviour if a user enters a string with more than 19 characters (without any white space in between), because you then exceed your userWord-array.
To overcome both, you could read in a line with fgets, then use sscanf to parse the line. Note that you can parse the line in one command; the result of scanf is then the number of successfully read items. Further, note the %19s, which limits the input to 19 characters (+ the final string termination character '\0'):
int main() {
char line[100];
if (fgets(line,100,stdin)) {
char userWord[20];
int userNum;
if (sscanf(line, "%19s %d", userWord, &userNum) != 2) {
printf("invalid input.\n");
} else {
printf("word:'%s'; number: %d", userWord, userNum);
}
}
}
I am new to c programming. I have created a program for entered letters and finally displayed the entered letters.. but it displayed only final letters always.. please help .. i know its simple question but am beginner so please help guys..
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%s\n",&z);
}
return 0;
}
Problems:
You should use %c (for character) instead of %s (for string).
Use a character array for storing multiple characters. Read about arrays here.
Remove & from printf() in the second for loop.
Try this:
int main()
{
char z[10]; //can hold 10 characters like z[0],z[1],z[2],..
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}
Please look into this for more details on scanf. You have given scanf("%s",&z); %s is for reading strings(array of chars except newline char and ended with null char). So if you put this inside loop you wont get desired result. And if you want read only a char at a time use %c here c for Character.
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
char z is a place holder for one character only. And you are over writing what you set z to in the for loop. To take in more characters, use a char array as others have mentioned.
Or print the characters in the same you loop you are scanning them:
#include<stdio.h>
int main()
{
char z;
int a;
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z);
printf("letter scanned:%c\n", z);
}
return 0;
}
Letters are scanned using %c. And to scan multiple letters you can use char array: char z[10];
What you are trying to do can be done this way:
char z[10]; // Take some max size array
...
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",&z[i]); // Scan the letters on each array position.
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]); //'printf' doesn't require address of arg as argument hence no `&` required
}
%s argument is used to scan a string of chars.
Note the difference between string of chars and array of chars. The string of chars in C needs to be terminated with ASCII Character 0 represented as \0 in char format, while the array of char is just a collection of letters which need not be terminated with \0.
The difference becomes more important when you try to perform some operation on strings such as printf, strcpy, strlen, etc.. These functions work on null character termination property of string.
For Example: strlen counts the characters in the string till it finds \0, to find out the length of string. Similarly, printf prints the string character by character until it finds the \0 character.
UPDATE:
Forgot to mention that scanf is not a good option to input char format. Use fgetc instead, with stdin as input FILE stream.
#include <stdio.h>
int main()
{
char *z;
int a;
printf("enter the no.");
scanf("%d",&a);
z = (char *) malloc(a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%c",z+i);
}
printf("the entered letters are:");
for(i=0;i<a;i++)
{
printf("%c\n",z);
}
return 0;
}
first error in your code is you have used "%s" instead of "%c".Second is it is impossible to store multiple values in one variable so instead of using variable use arrays.third is that you have told the user to enter the number of character that he/she wants to entered which you don't know.They can enter 1 also and 100000 also so the number of members in array is not defined.Better is to use specific number of characters in array.
finally i got the answer thank you for the help stackoverflow guys simply rocks ...
#include<stdio.h>
#include<malloc.h>
int main()
{
int a;
char *z=(char *)malloc(sizeof(a));
printf("enter the no.");
scanf("%d",&a);
printf("the entered no. is:%d\n",a);
int i;
for(i=0;i<a;i++)
{
printf("enter the letters:");
scanf("%s",&z[i]);
}
printf("the entered letters are:\n");
for(i=0;i<a;i++)
{
printf("%c\n",z[i]);
}
return 0;
}
So here is my program. It is suposed to write out square of some intiger.
#include <stdio.h>
int main (){
int a;
printf("Type an intiger.");
scanf("%i", &a);
printf("Square of that intiger is %i", a*a);
return 0;
}
When i run a program in Eclipse it first requires me to input a number.I put in 5. And then as output it gives me
Type an intiger.Square of that intiger is 25.
It should first print "Type an intiger" and then the rest. But it just combines two printf commands. What is the problem?
You need a newline character - printf("Type an intiger.\n");
In computing, a newline, also known as a line break or end-of-line
(EOL) marker, or simply break, is a special character or sequence of
characters signifying the end of a line of text.
Also format specifier for integer is %d
scanf("%d", &a);
printf("Square of that intiger is %d", a*a);
If you want it on separate lines you can always add '\n' to the string to get a new line.
#include <stdio.h>
int main (){
int a;
printf("Type an intiger.\n");
scanf("%i", &a);
printf("Square of that intiger is %i", a*a);
return 0;
}
There is 2 problem in it. First, if you input the integer, it should be %d. Example :
scanf("%d", &a);
The second, after the input, you should print \n. So, it will be like this printf("\n");. Take a look at my code :
#include <stdio.h>
int main (){
int a;
printf("Type an intiger.");
scanf("%d", &a);
printf("\nSquare of that intiger is %d", a*a);
return 0;
}
In code::blocks it compiles fine anyway put a \n at the end of the first printf and change %i with %d