I am currently just learning C and for a project I need to read in integer inputs from the user. Currently I am using code that looks like this:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int a, b;
printf("Please enter your first number");
while((a = getchar()) != '\n') {
}
printf("test");
return 0;
}
Im not sure how to get the number with getchar and then store it in a variable i can use.
Also I'm using = '\n' in the while statement because I don't really understand how EOF works (as in the K&R book) because whenever i use EOF i go into this loop i cant get out of.
Thanks for any advice anyone can offer.
You can use scanf.
Have a look at this example:
printf("Please enter your first number ");
int number=0;
scanf ("%d",&number);
The scanf answer above mine is correct, but if you haven't read about addresses or format strings, it may be difficult to grok.
You can convert your character to its integer equivalent by subtracting '0' from it:
char c = getchar();
int n = c - '0';
Related
Hey I am beginner in programming i need help to solve this problem
I want that i input some character and i want to print it..
#include<stdio.h>
int main()
{
char a[50];
printf("Enter character...");
scanf("%s",&a[50]);
printf("You entered is %s",a[50]);
return 0;
}
From the above code I am not getting any output i also try using loop but not get any result please help me what is correct program so that if i enter any string i print on the screen?
So here's your issue.
You are defining an array of type char with a length of 50. You then read from stdin a string, and then store it at the address of the 50th element. So what will happen is you are storing the string "out of bounds" and you may get a crash, or may not.
Either way, something very bad is happening. You are writing data to an area of memory that you should not be.
So what you want to do is write that data to the address of the 0th index of the array.
You do that by using &a[0] or, for simplicity's sake: a. Both mean the same thing.
At the end of the day, what you want is this:
#include<stdio.h>
int main()
{
char a[50];
printf("Enter character...");
scanf("%s",a);
printf("You entered is %s",a);
return 0;
}
I understand you are a beginner and are learning basic concepts, but keep in mind, this code is very unsafe. Because if someone types in a length of characters longer than 50, you are back in the same boat you were before.
Quoting kaylum's comment, "It would be beneficial to go through a basic C book or tutorial before proceeding further."
Now about your issue, change these lines:
scanf("%s",&a[50]);
printf("You entered is %s",a[50]);
to
scanf("%50s", a);
printf("You entered \"%s\".\n", a);
If you just want to print what's inputted by the user then you could use buffer:
#include <stdio.h>
int main(void)
{
char c;
printf("Enter the string(~ to exit)\n");
while((c = getchar()) != '~')
putchar(c);
return 0;
}
Output:
Enter the string(~ to exit)
This is a test program // press enter
This is a test program // same output
~ // exit
Why is this while loop not exiting ?
I want to input a series of number from users and then use them one by one for further processing. I do not have the size of numbers list. Can someone please tell me how to do this ?
#include<stdlib.h>
#include<stdio.h>
int main()
{
int x;
scanf("%d",&x);
while(x!='\n')
{
printf("%d",x);
scanf("%d",&x);
}
return 0;
}
Example:
Input:
3 5 6
Output:
3 5 6
Actual Output:
3 5 6
but loop doesn't exit
The %d conversion specifier never stores the \n into the buffer. It reads up to the \n in the buffer and leaves it there. So, this is essentially an infinite loop.
You may need to use a format specifier like %c which actually reads and stores the \n.
Although, if I may suggest, try to make use of getchar(), which reads the next character from the standard input and returns the value as an int. However, for an input of digits, you need to parse and store the integer and/or float value accordingly, but it will certainly provide you more flexibility.
What about this?
while(scanf("%d", &x) != EOF) {
printf("%d",x);
if (getchar() == '\n') break;
}
Why not use argv and strtol ?
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char **argv) {
int i = 0, x;
for(i = 1; i < argc; i++) {
x = strtol(argv[i],NULL,10);
printf("%d\n",x);
}
return 0;
}
while(scanf("%d",&x) != EOF) {
printf("%d",x);
}
...would do it. Don't ignore scanf returns. The reason your code is looping is you're really comparing x against decimal value of 10 ('\n'). Also, please remember that you asked scanf to give you integers and that's what it gives you, it will not give you newlines, even if it could.
Edited, so that I added comparison to EOF specifically.
You need to remember that scanf scans a stream, in this case the input stream, it will not return until that stream is done.
You should really use strings and sscanf() for what you want to do.
I'm slowly learning C. I read this page about input and output dealing with strings here: http://www.cprogramming.com/tutorial/c/lesson9.html
In the last code example, fgets is used to get and assign the input to a variable to the char array name. I tried implementing something similar in my own program.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
/* This is my very first C program! */
bool test=true;
/* Function Prototypes */
int mult(int x, int y);
/* Structures */
struct Person {
int age;
char name[256];
};
/* Complicated Array ;P */
struct Person *FirstPeriod[22];
char FakeString[100];
void PracticeStrings()
{
int i;
fgets(FirstPeriod[0]->name, 256, stdin);
for (i=0;i<256;i++)
{
if (FirstPeriod[0]->name[i]=='\n')
FirstPeriod[0]->name[i]='\0';
}
printf("\n\nHello Student 0: %s",FirstPeriod[0]->name);
}
int main()
{
struct Person DadeLamkins;
DadeLamkins.age=16;
int numb;
int x;
int *numb_address=&numb;
numb_address=malloc(sizeof(*numb_address));
FirstPeriod[0]=&DadeLamkins;
if (true)
printf("-__- \n\n");
printf("Please enter a number: ");
scanf("%d", &numb);
switch (numb) {
case 0:
printf("Dude, 0 is lame...\n");
break;
case 7:
printf("Dude, 7 is my favorite number!\n");
break;
default:
printf("You entered %d\n", numb);
break;
}
for (x=0;x<numb+1;x++) {
printf("\n::# %d",mult(x,2));
}
printf("\n\n%d",numb_address);
free(numb_address);
numb_address=0;
PracticeStrings();
getchar();
return 0;
}
int mult (int x, int y)
{
return x*y;
}
The PracticeStrings function on line 26 is the issue currently. When I compile, it displays Hello Student 0: before accepting the input (from fgets). I'm using Code::Blocks to compile.
Any help would be appreciated!
Edit...
Hahaha, yes, I understand that my program is inefficient and very silly. As you can tell, it doesn't really accomplish much. It is mostly just something to shove what I'm currently learning and try to apply things without actually rewriting the code examples (what do I learn if I copy word for word?). Anyways, thanks for the help! I guess that does make sense! It is too bad that my tutorials didn't mention that, I'm sure it is something that just takes a little bit of a higher understanding. I'm sure that the tutorial writer didn't expect anyone to mix the functions in the way I did.
Thanks a ton guys! Hopefully I can get used to this. I've done lots of scripting and plenty in the .net languages, hopefully I can add C to this list :)
It is because when you read the number:
scanf("%d", &numb);
stdin still has \n left in the buffer. So when you call PracticeStrings() and subsequently:
fgets(FirstPeriod[0]->name, 256, stdin);
You read \n and end up with
FirstPeriod[0]->name[i] == '\0';
Further, as you are learning, learn to validate :)
I.e.:
if ((foo = malloc(blah)) == NULL) {
... err ...
And even more critical:
if (scanf(..) != number_of_items_i_want) {
... did not get a number, or what ever I wanted ...
etc.
I think your issue is due to the behavior of your console, and your scanf() call.
The default setting for your console is probably line buffering. That means that nothing you type on your terminal is sent to stdin until after you have hit the enter key.
However, your call to scanf() (in main()) is only grabbing the integer that you've typed - not the trailing carriage return. Your carriage return is still sitting, unread, in stdin until the fgets() call in line 26.
One way around that is to get scanf() to consume the trailing carriage return too:
scanf("%d%*c", &numb);
Which reads the integer from stdin into &numb, and reads (and discards) an extra character.
This all hilights one of the big problems with the use of scanf(), which is how to make it cope in the event that you get a string that you weren't expecting.
A safer way is to use a combination of fgets() and sscanf(). The former will let you read a string from a file (as you've done), and the latter will run a formatting string over it.
eg.
char temp[20];
fgets(temp, 20, stdin);
sscanf(temp, "%d", &numb);
I have declared a char variable ope in function main.
i took the input through getchar function and stored in ope.
Now i want to blank the variable so i will be able to store some other in ope.
Can anybody show me how to do it??
I just want to continuously store the input in ope variable. If it's possible through some other way, kindly guide me. I will be very thankful.
You can reuse the getchar() function same way you used it first time.
Here is sample code from the cplusplus.
#include <stdio.h>
int main ()
{
char c;
puts ("Enter text. Include a dot ('.') in a sentence to exit:");
do {
c=getchar();
putchar (c);
} while (c != '.');
return 0;
}
You don't need to blank it, just do getchar() once again.
Eventualy set it to or "0 char"
c = '\0'; or c = 0;
When I compile the C codes (from Teach yourself C, 2nd edition-Herbert Schildt) written below in Borland C++ v5.02, I get a warning message as below:
"c61.c(7,6): Conversion may lose significant digits"
What's wrong?
#include "stdio.h"
main()
{
char ch;
ch = getchar();
printf(" You typed: %c", ch);
return 0;
}
Same problem with another example:
#include "conio.h"
#include "stdio.h"
main()
{
char ch;
printf("Enter a character: ");
ch = getche();
printf("\nIts ASCII code is %d", ch);
return 0;
}
getchar() returns an int, so that it can return non-character values like EOF. So when you store the return value in a smaller datatype, like a char, you are potentially losing information.
Schildt's books are commonly considered the worst available for learning C (or C++) and this is a good example of why. You would be well advised to get a better book, such as K&R.
The prototype for getchar is:
int getchar (void);
It returns an int because it needs to return EOF which is not a character.
Expanding on that, the function needs to be able to return any valid character, as well as being able to return a special "character" indicating that you're reached the end of file (or an error has occurred).
Since a char data type can only hold one of the characters, there would be no way to indicate this end of file if all the function returned was a char. That's because, if you selected one of those char values to represent end of file, you would not be able to tell the difference between the end of file and the actual character.
For example, let's choose 'A' to indicate end of file. When you actually get back an 'A' from getchar(), how will you know whether you've reached the end of file or whether the user actually entered 'A'?
To get around this, many functions that give you back a char will actually give you an int and use one of the integer values which don't have an actual char equivalent (such as -1).
In that case (assuming an 8-bit char), you would get back either a -1 if you've reached the end of the file or a value from 0 through 255 inclusive representing the character entered.
And you need to get yourself both a more modern book and a more modern compiler:
#include <stdio.h>
int main (void) {
int ch = getchar();
if (ch != EOF)
printf("You typed: %c\n", ch);
return 0;
}
Why anyone is still using Borland is this day and age (where gcc is both just as cheap and much better) is beyond me.
What about this alternative program? It works fine.
#include <stdio.h>
main()
{
char ch;
getchar();
printf("Enter the character: ");
scanf("%c", &ch);
printf(" You typed: %c\n", ch);
return 0;
}
Please leave some comments.