Ok I am making a program that reads two characters from the user and then prints the ASCII letters between those two characters.
The problem is that when the program runs it prompts the user to enter the first character and once the user hits enter the program ends.
What am I missing?
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
char firstchar;
char secondchar;
int variable;
int highest;
int lowest;
char ASCIvariable;
printf("Please enter a character. ");
scanf("%d", &firstchar);
printf("Please enter another character. ");
scanf("%d", &secondchar);
if(firstchar < secondchar)
{
secondchar = highest;
firstchar = lowest;
}else{
firstchar = highest;
secondchar = lowest;
}
variable = lowest;
for ( variable != highest; variable < highest; variable++ )
{
variable = ASCIvariable;
printf(ASCIvariable);
}
return 0;
}
I clearly also don't understand how to post code on this site. I need four spaces manually entered before EVERY line of code?
Update here is the current code also control k will not allow paste....
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
char firstchar;
char secondchar;
int variable;
int highest;
int lowest;
char ASCIvariable;
printf("Please enter a character. ");
scanf(" %c", &firstchar);
printf("Please enter another character. ");
scanf(" %c", &secondchar);
if(firstchar < secondchar)
{
highest = secondchar;
lowest = firstchar;
}
else
{
highest = firstchar;
lowest = secondchar;
}
variable = lowest;
for (variable != highest; variable <= highest; variable++ )
{
ASCIvariable = variable;
printf("%c ", ASCIvariable);
}
return 0;
}
It successfully allows the user to enter both characters and then prints the letters between the two. I think that is correct?
Using wrong format specifier might lead to UB. You need to scan a character
scanf("%c", &firstchar);
Then flush the newline char using
scanf(" %c",&secondchar);
The space before the %c consumes the newline char.
1)You must get input with format specifier %c for characters
2)You must consume the newline after entering first character
3) You seem to be confused with assignment statements
a=b
assigns the valure of b to a and not the other way around.
printf("Please enter a character. ");
scanf(" %c", &firstchar);
//The space before %c will consume the newline
printf("Please enter another character. ");
scanf(" %c", &secondchar);
if(firstchar < secondchar)
{
highest=secondchar ;
lowest=firstchar ;
}
else
{
highest=firstchar;
lowest= secondchar ;
}
//Changed the for loop to get characters between two inputs
variable = lowest+1;
for ( ; variable < highest; variable++ )
{
ASCIvariable= variable ;
printf("%c ", ASCIvariable);
}
Change your code to:
printf("Please enter another character. ");
scanf(" %c", &secondchar); /* Note the extra space and %d is changed to %c*/
Also change your for loop to:
for ( ; variable <= highest; variable++ ) /* Should be <= */ {
ASCIvariable = variable; /* Reverse */
printf("%c", ASCIvariable); /* %c */
}
Your assignations are also incorrect:
if(firstchar < secondchar)
{
highest = secondchar;
lowest = firstchar;
}
else
{
highest = firstchar;
lowest = secondchar;
}
a = b; means copy contents of b into a.
Related
I want to write a program, at first I input a number N, then I want to get the name (can consist of multiple words) and price of N items one by one. Example:
3
item a // the name can consist of multiple words
25.00
item b
12.50
item c
8.12
Next I want to process this data, however i got stuck on the scanning part. my code looks like this:
#include <stdio.h>
int main(){
int n;
char name[50];
int price;
scanf("%d\n", &n);
for(int i = 0; i < n; i++){
scanf("%s\n%d",name,&price);
printf("%s , %d", name, price);
}
printf("end");
}
This works for a single word item, but if the item has a space in it will not continue scanning. I tried using the gets() function, however I still don't have the right result. the code:
for(int i = 0; i < n; i++){
gets(name);
scanf("%d\n",&price);
printf("%s , %d\n", name, price);
}
printf("end");
returns:
3 // Input 3 items
item a // name of first item
1 // price of item 1
item b // name of item 2
item a , 1 // the print of the first item
2 // price of item 2
item c // name of item 3
item b , 2 // print of item 2
3 // price of item 3
word // no clue where this new input came from
end // end of scanning
My question is, how would I go about correctly scanning an input such as this? I also tried changing the scan function into while((c = getchar()) != '\n');, but got the same result...
Mixing gets(), scanf() is bad as scanf() tends to leave the trailing '\n' in stdin.
Using gets() is bad.
scanf("%s", ...) is not useful for reading a line of info with spaces meant to be saved.
how would I go about correctly scanning an input such as this?
A simple alternative is to read each line into a string and then parse the string.
#include <stdio.h>
int main() {
char line[100];
int n;
fgets(line, sizeof line, stdin);
sscanf(line, "%d", &n);
for(int i = 0; i < n; i++){
char name[50];
// int price;
double price;
fgets(line, sizeof line, stdin);
sscanf(line, " %49[^\n]", name);
fgets(line, sizeof line, stdin);
// sscanf(line, "%d", &price);
sscanf(line, "%lf", &price);
printf("%s , %.2f\n", name, price);
}
printf("end");
}
Advanced: Better code would check the return values of fgets(), sscanf(). Maybe replace sscanf(line, "%lf",... with strtod().
I think you could probably figure out what's happening here pretty easily if you added some more output. Let's try shall we?
Also, first of all you're really looking for a double input - not an integer. With an integer, your scan function won't match properly based on what you're looking for. But let's add some more output!
#include <stdio.h>
int main()
{
int n;
char name[50];
double price;
printf("Enter count: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
printf("%s\n", "Please type a name followed by a newline followed by a number and then press enter:");
scanf("%s\n%lf", name, &price);
printf("%s , %lf", name, price);
}
return 0;
}
So I think what was happening in your initial attempt was a combination of things. Mostly that you were possibly pressing enter after the output from the first iteration? That will break the scanf call - since it isn't expecting to start with a \n but it is immediately expecting you to enter a name.
Second, I don't know the number you entered in the first iteration, because you didn't supply the output of it while still using scanf - so I have nothing other than speculation. You possibly used an integer on the first go, and subsequently on the remaining iterations you chose to use decimals? Again, this is only a guess.
Sometimes it is easier to just write your own functions with error checking. Below is a suggestion. You may also want to check that the numbers are non-negative.
#include <assert.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
void ReadLine(char result[], int resultLen)
{
int ch, i;
assert(resultLen > 0);
i = 0;
ch = getchar();
while ((ch != '\n') && (ch != EOF)) {
if (i < resultLen - 1) {
result[i] = ch;
i++;
}
ch = getchar();
}
result[i] = '\0';
}
void ReadInteger(int *i)
{
int ch, count;
count = scanf("%d", i);
if (count == 1) {
do {
ch = getchar();
} while (isspace(ch) && (ch != '\n'));
} else {
fprintf(stderr, "invalid input, integer expected\n");
exit(EXIT_FAILURE);
}
}
void ReadReal(double *x)
{
int ch, count;
count = scanf("%lf", x);
if (count == 1) {
do {
ch = getchar();
} while (isspace(ch) && (ch != '\n'));
} else {
fprintf(stderr, "invalid input, real number expected\n");
exit(EXIT_FAILURE);
}
}
int main(void)
{
char name[50];
int n;
double price;
ReadInteger(&n);
for (int i = 0; i < n; i++) {
ReadLine(name, sizeof name);
ReadReal(&price);
printf("%s, %.2f\n", name, price);
}
return 0;
}
As chux said in the comments of this answer: "All scan specifiers, except %c, %[, %n consumes leading white-spaces." So you don't need to account for them.
scanf("%s%d",name,&price);
And looking at your input, you should use float or double for the price.
scanf("%s%lf",name,&price);
Note that this works only if items are made of one word. If they can be of two or more words, you'd better use fgets
EDIT: for items made of more words you should use fgets
fgets(name, 50, stdin);
scanf("%lf",&price);
Replace your for loop with this:
for (int i = 0; i < n; i++) {
scanf(" %[^\n]\n%d", name, &price);
printf("%s , %d\n", name, price);
}
The first space skips leading spaces, and the [^\n] allows you to get more than one word as string input.
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.
The following program is from a homework assignment.
I need to write a program where it:
asks a Seed and a Range,
generates and displays a sequence of random numbers based on the seed and range input,
converts the above into a sequence of "A"s, "B"s, or "C"s depending on the generated sequence: turn 1 into A, 2 into B, 3 into C;
asks whether to continue; if user puts "n", stop; else starts over again.
#include <stdlib.h>
#include <stdio.h>
int main() {
int seed;
int Range;
char ch;
while (ch != "n") {
printf("Enter a seed: ");
scanf("%d", &seed);
printf("Enter a Range: ");
scanf("%d", &Range);
srand(seed);
for (int i = 0; i < 10; i++) {
scheduler(rand() % Range + 1);
}
printf("Continue?\n");
scanf("%c", &ch);
}
return 0;
}
I put two arbitrary numbers and it generates a random sequence as expected. But then it just prints "Continue?" without taking an input from me and then asks me to enter a seed. What's wrong with my code? What's the proper way to do this?
Change this:
scanf("%c", &ch);
to this:
scanf(" %c", &ch);
in order to eat the leftover character (the newline character you pressed when you entered the numbers (seed andRange`) before).
I had wrote more about that issue here.
Moreover, your code invokes Undefined Behavior (UB), since you check ch before it gets initialized here:
char ch;
while (ch != "n") {
...
}
Use a do-while loop structure instead, like this:
do {
...
} while (ch != 'n');
Furthermore, you should get a compiler warning like this:
warning: comparison between pointer and integer
while (ch != "n") {
^~
warning: comparison with string literal results in unspecified behavior [-Waddress]
Change "n" to 'n', since ch is of type char, not char*.
Putting everything together, your code should like this:
#include <stdlib.h>
#include <stdio.h>
int main() {
int seed;
int Range;
char ch;
do {
printf("Enter a seed: ");
scanf("%d", &seed);
printf("Enter a Range: ");
scanf("%d", &Range);
srand(seed);
for (int i = 0; i < 10; i++) {
scheduler(rand() % Range + 1);
}
printf("Continue?\n");
scanf(" %c", &ch);
} while (ch != 'n');
return 0;
}
#include <stdlib.h>
#include <stdio.h>
int main()
{
int seed;
int Range;
char ch = '\0'; /* initialize ch to something other than 'n' */
/* if ch not initialized, u take your chances on being able to enter while loop */
while (ch != 'n') / single quote characters, double quote for strings imply null character \0 after last character in string */
{
printf("Enter a seed: ");
fflush( stdout ); /* because of no \n in printf */
scanf("%d", &seed);
printf("Enter a Range: ");
fflush( stdout ); /* because of no \n in printf */
scanf("%d", &Range);
srand(seed);
for (int i = 0; i < 10; i++)
{
scheduler(rand() % Range + 1);
}
printf("Continue?\n"); /* bet u this works, because of \n */
scanf("%c", &ch);
}
return 0;
}
Hi how would you count the number of occurences in the given word like shown below because with the program I have right now it doesn't seem to room correctly.
#include <stdio.h>
int main(void)
{
char a;
char lang[] = "pneumonoultramicroscopicsilicovolcanoconiosis";
char i = 0;
char count = 0;
printf("pneumonoultramicroscopicsilicovolcanoconiosis\n");
printf("\nEnter the letter you want to find the number of\n");
scanf("%c", &lang);
for (i = 0; i <= 46; i++)
if (a == lang[i]) {
count++;
}
printf("Number of %c is %d..\n", a, count);
return 0;
Your scanf is the problem.
Try:
scanf("%c",&a);
declare count as int instead of char
also change scanf to take input a
#include <stdio.h>
int main(void)
{
char a;
char lang[] = "pneumonoultramicroscopicsilicovolcanoconiosis";
char i = 0;
int count = 0;
printf("pneumonoultramicroscopicsilicovolcanoconiosis\n");
printf("\nEnter the letter you want to find the number of\n");
scanf("%c", &a);
for (i = 0; i <= 46; i++)
if (a == lang[i]) {
count++;
}
printf("Number of %c is %d..\n", a, count);
return 0;
}
You probably shouldn't hard code the max length of the string (46) if at all possible in case you are given a longer string, but assuming it's an assigned assignment that is set it shouldn't be a problem.
i and count should also be ints if possible for a bigger size count. And &lang should be &a since lang is already assigned while a is your checker.
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;
}