take user's input and then print the alphabet series - c

My aim is to take user's input and then print the alphabet series. Printing the alphabet series from the point the user entered the input.
#include<stdio.h>
int main(){
char alpha_U;
printf("Enter the letter from where you want in upper case: ");
scanf("%c",alpha_U);
for(char i = alpha_U; i <= 'Z'; i++){
printf("%c",i);
}
return 0;
}

Your code is almost fine, except for
scanf("%c", alpha_U);
which requires a pointer as second argument.
I am not expert of C or C++ programming, so the thing I would suggest you is to checkout the documentation on cplusplus.com.
Specifically, here is how scanf is documented:
https://cplusplus.com/reference/cstdio/scanf/
The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string.
so in your case you should be doing
scanf("%c", &alpha_U);

I am also starting out with C so I apologize if I missed any details.
scanf("%c", alpha_U);
is missing & in the front of the variable. Corrected below.
scanf("%c",&alpha_U);
I rewrote the code so I can get the user input in the main function.
#include<stdio.h>
#include <ctype.h>
int main(int argc, char *argv[]){
char lowerCase,upperCase;
printf("Enter one chacters to be capitalized\n");
scanf("%c", &lowerCase);
upperCase = toupper(lowerCase);
printf("%c",upperCase);
return 0;
}

#include<stdio.h>
int main()
{
char alpha_U;
printf("Enter the letter from where you want in upper case: ");
scanf("%c", &alpha_U);//Here,you should add '&' before 'alpha_U'
for (char i = alpha_U; i <= 'Z'; (int)i++) {//Then,add '(int)' before 'i'
printf("%c", i);
}
return 0;
}

Related

Ensuring you're reading a character through scanf

Is there a simple way to make sure you're reading a character through scanf. If it were an integer I'd use a do while loop
do{
printf("enter a number");
fehler = scanf(" %d", &x);
getchar();
} while(fehler!=1);
But I'm not fully sure what to do if the input is meant to be a string. I know the alphabets are stored as ASCII values but the if constraints in the while statement don't seem to be working(unless I'm doing it wrong)
char * temp2;
temp2 = malloc(sizeof(string));
do{
printf("PLease enter a string: ");
scanf(" %s", temp2);
getchar();
} while(temp2 <= 'A' && temp2 <= 'z')
You can't compare a string to a single character. You have to loop through the entire string, checking every character.
#include <ctype.h>
int is_alphabetic(char *str) {
for (int i = 0; str[i]; i++) {
if (!isalpha(str[i])) {
return 0;
}
}
return 1;
}
...
do{
printf("Please enter an alphabetic string: ");
scanf(" %s", temp2);
getchar();
} while(!is_alphabetic(temp2));
You see printf and scanf work independently. Whatever you store be it a character or number is stored in form of a number. Now it depends on the printf function what it demands.
Eg.: If you store 'a' at a location, the number 97 is stored. Now if you print a number it prints 97 and if you demand a character it gives a.
#include <stdio.h>
int main()
{
int i = 97;
printf("%d \n", i);
printf("%c", i);
return 0;
}
See the results. Further char, int , long int are just data types which specify the number of bits that would be resrved for the inputs for the variable.
Execute this program and you'll understand:
#include <stdio.h>
int main()
{
int i;
for (i=97; i <=200 ; i++)
{
printf("%d %c,\t",i,i);
};
return 0;}
This will show you a nmber when printed as a number and then the SAME number read as character.
Note there are no markers in memory to store which type of data it is. It is straightforward stored as number.
scanf is absolutely the wrong tool for this. But if you want to read only alphabetic characters, you can do it easily enough with something like:
char s[32];
if( 1 == scanf(" %31[a-zA-Z]", s) ){ ... }
The %31[a-zA-Z] conversion specifier will match only the literal characters a thru z and A thru Z, and will only consume up to 31 characters of input. You must always use a field width modifier with %s or %[] conversion specifiers to avoid an overflow.

Frequency function in C

I wrote a program that should take a string and a letter, then call a function which have two parameters (the string, the letter) and then count frequency of letter in the string.
The problem with my code is that it always returns num with value zero for any letter.
#include <stdio.h>
#include <stdlib.h>
int Occur(char [], char);
int main()
{
char s[100], l;
printf("Enter A String:\n");
scanf("%s",s);
printf("Enter A Letter:\n");
scanf("%c",&l);
getchar();
printf("Num Of Occurance is %d ",Occur(s,l));
return 0;
}
int Occur(char S[100], char L)
{
int i;
int num=0;
for(i=0; S[i]!='\0'; i++)
{
if(S[i]==L)
num++;
}
return num;
}
First, you should have tried debugging your code. If you would have done it, you would have seen that the letter you thought L holds is not what L actually holds.
Second, your problem is simple, L is not getting the letter you enter because of the enter from the string before is stuck in the scanf buffer... use scanf (" %c") [with preceeding whitespace] to resolve.
As mentioned in other answers, there are other solutions like the unrecommended fflush(). An alternative that is not considered harmful is getchar() between the scanf("%s") and the scanf("%c"). That will give you the same effect as using scanf(" %c");
The reason that all of these methods work is because they all consume the last char (which is, in your case the \n) stuck in the buffer, and thus allowing the %c to consume the char you actually intend to read
Reason of problem :
scanf("%c",&l) //Here %c takes enter key of scanf("%s",s);;
So, there are mainly 2 solution to your problem:
Sol. 1 => scanf(" %c",&l) //use whitespace before %c
Sol. 2 => Use fflush(stdin) that flushes the output buffer of a stream.
int main()
{
char s[100],l;
printf("Enter A String:\n");
scanf("%s",s);
printf("Enter A Letter:\n");
fflush(stdin); //here fflush(stdin) used to flushes the output buffer.
scanf("%c",&l);
l = getchar();
......
......
}
NOte: Since fflush(stdin) has undefined behavior so, always use priority to Solution 1 , instead of fflush(). :)
It's an input buffer problem. The char is read by getchar instead of scanf.
Doing l = getchar() solves the problem (the call of scanf just before clears the input buffer).
#include <stdio.h>
#include <stdlib.h>
int Occur(char [],char);
int main()
{
char s[100],l;
printf("Enter A String:\n");
scanf("%s",s);
printf("Enter A Letter:\n");
scanf("%c",&l);
l = getchar();
printf("Num Of Occurance is %d ",Occur(s,l));
return 0;
}
int Occur(char S[100],char L){
int i;
int num=0;
for(i=0;S[i]!='\0';i++){
if(S[i]==L)
num++;
}
return num;
}
Your function definition is wrong in terms of good code practices.
Instead of
int Occur(char S[100], char L)
You should write it as
int Occur(char S[] , char L)
because otherwise your code would specifically look to accept strings of size not more than 100 chars.
Apart from that as Ilario Pierbattista said its a input buffer problem.
The stdin needs to get cleared before taking further input, hence the juggad of putting scanf before a getchar() call would work.

How to make a user input sentence into all capital letters in C?

I need to take a user inputted sentence and make it all capital letters. However, I can not use strings yet so I was thinking that I need to use the toupper function to make it work.
However, when I run the code below it didn't print anything in capital / uppercase. I was also thinking that I might not use scanf but like a getchar instead but I'm not sure.
#include <stdio.h>
#include <ctype.h>
int main ()
{
char sen;
printf("Enter sentence");
scanf("%c", &sen);
putchar (toupper(sen));
printf("The caps are:%c\n", sen);
return 0;
}
Try this, (no strings involved ! ):
#include <stdio.h>
#include <ctype.h>
int main ()
{
char c,u;
printf("Enter sentence, press [enter] key to end");
while(c=getchar()!='\n')
{
u=toupper(c);
putchar (u);
}
return 0;
}
This converts characters, one at a time, to uppercase, and prints them, again one at a time, until the enter/return key is hit, which will make the program quit.
#include<stdio.h>
main()
{
char str[100]="",i;
printf("Enter a sentence\n");
scanf("%[^\n]",str);
for(i=0;str[i];i++)
{
printf("%d\t%c\n",str[i],str[i]);
if( (str[i]>=97) && (str[i]<=122) )
str[i]-=32;
}
printf("Caps sentence is %s\n",str);
}
Here's what you could do:
1) You need a char array to store the sentence char sen[80];
2) Change scanf("%c", &sen); to scanf("%s", sen); since you're not inserting a single character.
3) Use a loop to change every char in the array to upper case:
for (int i = 0; i < 80; i++) {
sen[i] = toupper(sen[i]);
}
4) Change: printf("The caps are:%c\n", sen); to printf("The caps are: %s\n", sen);
int main ()
{
char sen[80];
printf("Enter sentence: ");
scanf("%s", sen);
for (int i = 0; i < 80; i++) {
sen[i] = toupper(sen[i]);
}
printf("The caps are: %s\n", sen);
return 0;
}
You need a char array,say it letter to store the sentence typed by user.
Here first for loop is to read in the sentence char by char using getchar function,and then putchar function is used to print character in uppercase.
#include<stdio.h>
#include<ctype.h>
#define EOL '\n'//EOL stands for end of line character.
int main()
{
char letter[80];
int tag,count;
for(count=0;(letter[count]=getchar())!=EOL;++count)
tag=count;
for(count=0;count<=tag;++count)
putchar(toupper(letter[count]));
return 0;
}

c programming - printing sentences

this is my first time using this site as well as learning c programming.
I'm trying to write a code which lets a user type in a sentence and the code prints it back out.
My attempt:
#include<stdio.h>
int main()
{
char array[1000];
printf("Please enter a phrase: ");
int index = 0;
while(array[index]!= '\0')
{
scanf("%c",&array[index]);
++index;
}
index = 0;
while(array[index]!= '\n')
{
printf("%c",array[index]);
++index;
}
}
I can't find the reason to why this code does not work.
You can get expected output using your concept also.. Try something using following code.
#include<stdio.h>
int main()
{
char array[1000];
printf("Please enter a phrase: ");
int index =0;
scanf("%c",&array[index]);
while(array[index]!='\n')
{
scanf("%c",&array[++index]);
}
index=0;
while(array[index]!= '\n')
{
printf("%c",array[index]);
++index;
}
printf("\n");
}
Okay, so first and foremost you'll need to initialize all your array. If you don't, the user input will print along with lots of meaningless garbage.
Secondly, the test portion of your first while loop checks for a null character which will never exist because "array[]" is just a simple character array (not a string) therefore, a call to scanf() doesn't insert the null character at the end. This causes an infinite loop.
Thirdly, your first while loop should be a do-while so that you first read a character, then test the character, otherwise if the "index" variable increments first...
Lastly, I posted the code that i used to get it to run using the method that you chose. However, as an alternative to the method you chose, the c standard library has the gets() function, which will allow you to read an entire line of input and return the string entered (actually it returns a pointer to the character array created but i think you catch my drift), and the puts() function which prints a string pointed to by the pointer used as an argument.
For more info on this problem in general, including gets() and puts(), refer to "C Programming A Modern Approach" by K.N. King, Chapter 13: Strings.I hope this helps.
Happy Coding!! :)
#include <stdio.h>
int main()
{
int index = 0;
char array[1000];
while(index < 1000){
array[index] = '0';
index++;
}
printf("Please enter a phrase: ");
index = 0;
do {
scanf("%c", &array[index]);
} while(array[index] != '\n' && index++ < 1000);
index = 0;
while(index < 1000)
printf("%c", array[index++]);
}
I think your looking for this:
#include<stdio.h>
int main() {
char array[1000];
printf("Please enter a phrase: ");
scanf ("%[^\n]%*c", array);
printf("\n%s", array);
return 0;
}

How to invalidate an input in c

I'm writing a program in C that is suppose to ask the user for a number.
The number has to be greater than zero and cannot have letters before or after the number. (ie: 400 is valid but abc or 400abc or abc400 is not). I can make my program invalidate everything besides 400abc. How would I make it invalidate an input if it starts valid then turns invalid? (I'm about 2 months into an intro to c class so my knowledge is very limited.)
#include<stdio.h>
int check(void);
void clear_input(void);
main()
{
int num;
printf("Please enter a number: ");
num = check();
printf("In Main %d\n", num);
}
int check(void){
int c;
scanf("%d", &c);
while (c < 0){
clear_input();
printf("Invalid, please enter an integer: ");
scanf("%d", &c);
}
return c;
}
void clear_input(void){
char junk;
do{
scanf("%c", &junk);
}while (junk != '\n');
}
You can also check whether ascii value of each char scanned from user input should lie in range 48-57, It will only then be integer value.
strtol can be used to do it, but it takes some extra work.
After running this code:
char *endptr;
int n = strtol(num_text, &endptr, 10);
n will contain the number. But you still have to check that:
1. *endptr=='\0' - this means strtol didn't stop in the middle. In 400abc, endptr will point to abc. You may want to allow trailing whitespace (in this case, check that endptr points to an all-whitespace string.
2. num_text isn't empty. In this case, strtol will return 0, but an empty string isn't a valid number.
Read the input as a line, using fgets.
Check if all characters are numeric.
If not, it's invalid. If yes, use sscanf to get the line into an int.
Check if the int is in the range; you're done.
Scanf with %d will treat the "400abc" as 400, all the trailing characters would be ignored, so there is nothing to worry about.
If you definitely want to treat "400abc" as an invalid input, then maybe you shouldn't use %d in scanf, use %s instead?
One way is to read the whole line as a string and check by yourself if it contains any non-digits.
The other way is reading the integer and then looking into the input using fgetc() to see if the next character after the detected input is valid. Or you could even use the same scanf() for this:
char delim;
if(scanf("%d%c", &c, &delim) == 2 && !isspace(delim))
// the input is invalid
You can read the number in a character array and validate it by checking if all the characters lie in the ascii range 48 to 57 ( '0' to '9' ) .If so your no. is valid otherwise you can safely regard it as invalid input.Here the the demonstration :
#include<stdio.h>
#include<string.h>
int conv( char * word )
{
int ans=0;
int res=0;
for(int i=0;i<strlen(word);i++)
if(word[i]>='0' && word[i]<='9')
ans=(ans*10) + (word[i] - '0');
else
res=-999;
if(res==-999)
return res;
else
return ans;
}
int main()
{
char a[10];
gets(a);
int b=conv(a);
if(b==-999)
printf("Invalid Entry.\n");
else
printf("Success.No is %d.\n",b);
return 0;
}
You can adjust for negatives as well by checking the first character in the word array to be '-' and adjusting the sign accordingly.
This is C99, so compile with -std=c99
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
bool getNum(int *n) {
char c, s[10];
if (!scanf("%9s", s))
return false;
for (int i=0; c=s[i]; i++)
if (!isdigit(c))
return false;
*n = atoi(s);
return true;
}
int main() {
int n;
if (getNum(&n))
printf("you entered %d\n", n);
else
printf("you did not enter a number\n");
}
The following is your check function rewritten to fix your problem, so try this:
int check(void){
int n;
char c;
while (EOF==scanf("%d%c", &n,&c) || n < 0 || !isspace(c)){
clear_input();
printf("Invalid, please enter an integer: ");
}
return n;
}

Resources