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.
Related
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;
}
How can I introduce multiple strings in input and output with scanf()? Is it possible to do that without using 100 notations (e.g. a, b, c, d, e -> "%c %c %c", a, b, c etc.)?
I type this:
#include <stdio.h>
int main()
{
char user_str[20];
scanf("%s", user_str);
printf("%s", user_str);
return 0;
}
Which works for the first word as input and output, but if I want to introduce 100 propositions with space in the text, how can I type the code to do that in the easiest way possible?
As #Yunnosch notes, your best best is to use loops and arrays. Consider a simple situation where you want to read in 4 strings that are up to 19 characters in length. We have length 20 to leave space for a terminating null character.
#include <stdio.h>
int main() {
char input[4][20];
for (int i = 0; i < 4; i++) {
scanf("%19s", input[i]);
}
for (int i = 0; i < 4; i++) {
printf("%s\n", input[i]);
}
}
This is readily scalable to 100s of strings. If you use enough memory, you may wish to use malloc to allocate it, but the same basic pattern would continue.
Here is a solution which reads one line of input using scanf:
#include <stdio.h>
int main()
{
char user_str[20];
scanf("%[^\n]s", user_str);
printf("%s", user_str);
return 0;
}
Using %[^\n]s instead of %s will read all characters until you reach \n (or EOF ) and write them into user_str. But this solution is worse than gets(), so try to use fgets() instead.
#include <stdio.h>
int main()
{
char user_str[100];
printf("Enter your name: ");
fgets(user_str, 100, stdin);
printf("Your Name is: %s", user_str);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include<assert.h>
#define MAX_CHARACTERS 1005
#define MAX_PARAGRAPHS 5
char* get_input_text() {
int paragraph_count;
scanf("%d", ¶graph_count);
char p[MAX_PARAGRAPHS][MAX_CHARACTERS], doc[MAX_CHARACTERS];
memset(doc, 0, sizeof(doc));
getchar();
for (int i = 0; i < paragraph_count; i++) {
scanf("%[^\n]%*c", p[i]);
strcat(doc, p[i]);
if (i != paragraph_count - 1)
strcat(doc, "\n");
}
char* returnDoc = (char*)malloc((strlen (doc)+1) * (sizeof(char)));
strcpy(returnDoc, doc);
return returnDoc;
}
int main()
{
char* text = get_input_text();
printf("%s",text);
return 0;
}
Input
2
Learning C is fun.
Learning pointers is more fun.It is good to have pointers.
If I remove getchar();. Program doesn't work, Why is that?
Other wise code works fine and prints the the exact input as output.
when you try to give input to this scanf("%d", ¶graph_count); you will enter an integer and then press enter key ,scanf will take the exact input you said, which means the integer , but leaves \n produced by enter key in buffer so if you don't use getchar(); the next scanf (scanf("%[^\n]%*c", p[i]);) will take \n as the input character. but when you use getchar() this function will take that \n from buffer and
next scanf will work fine.
scanf("%[^\n]%*c", p[i]); Means read a line and then ignore a char ('\n').
In scanf("%d", ¶graph_count) you read a int but left a '\n' in buffer.
So you need getchar() to ignore a '\n', or you next scanf will meet a '\n' at the begining and read nothing.
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;
}
Can someone explain or correct me on the code i have?
I'm trying to input several characters and get the ascii value
ex: input: ab; output:9798
This is my code but there's a 10 at the end of it
#include <stdio.h>
int main() {
char c;
printf("Enter any character\n");
for (c=0; c<=122; c++)
{
scanf("%c", &c);
printf("%d",c);
}
return 0;
}
If you look at ASCII table, a decimal value of 10 is a newline character. In other words, you process \n character as part of the input. This can happen when user copy-pastes multiple lines, or when Enter key is pressed, for example. If you do not want that to happen, you need to take extra care to ignore \n. For example:
#include <stdio.h>
int main() {
char c;
printf("Enter any character\n");
for (c=0; c<=122; c++)
{
scanf("%c", &c);
if (c == '\n')
break; /* Or perhaps continue? Depends on what you actually want. */
printf("%d",c);
}
return 0;
}
Also, note that different systems may have different conventions as for what newline actually is. On UNIX, it is \n character only, on Windows, it might be a combination or \r and \n. So if you want to make your program portable, this needs to be taken into account. You can either do it yourself, or use some other library (GNU getline comes to mind). You can read more about newline here.
You may want to exclude some chars from the output and not only '\n', in that case you can try something like this:
#include <stdio.h>
int isEndingChar(char c) {
char terminators[3] = {'\r','\t','\n'}
int n;
for( n=0; n<3; n++ ) {
if( terminators[i]==c )
return 1;
}
return 0;
}
int main() {
char c;
printf("Enter any character\n");
for (c=0; c<=122; c++)
{
scanf("%c", &c);
if( isEndingChar( c ) )
break;
printf("%d",c);
}
return 0;
}