i want to write a math test
EX:i input a right number,then i can get point.
finally,i can get the total score.
there is my attempt.
but,when i input a wrong number,i always get point.
what should i do?
char a;
int b;
char d;
b=0;
printf("1+1=\n");
a=getchar();
if(a=2){
printf("you got%d \n",b=b+10);
}else{
printf("you got%d \n",b);
}
printf("1+2=\n");
d=getchar();
if(d=3){
printf("you got%d \n",b=b+10);
}else{
printf("you got%d \n",b);
}
return 0;
You need to use if (a == '2') rather than if (a=2).
The former:
tests the value of a, unlike the latter which assigns a
compares a with the character '2', rather than the number 2.
If you are trying to compare in the If statement, then you should use comparison operator == and not assignment operator =.
Also if you're comparing characters , you need to use character quotes ''
Eg.
if(a=='2')
{
printf("you got%d \n",b=b+10);
}
Related
I´d like to check if user input is a float/integer or a letter. For this purpose the use of scanf() is important. My problem is that a letter is saved as zero but I can´t exclude it.
I tried building solving it with if and as a condition I tried isalpha() and is digit().I tried a bunch of other things, but it´s not worth mentioning.
If the actual requirement is something like this:
Read a series of numbers (integers or floating-point numbers) from the user. Stop reading when the user types something other than a number, such as a letter.
, then the solution, using scanf, is perfectly straightforward:
#include <stdio.h>
int main()
{
int maxnums = 10;
double numbers[maxnums];
int i;
for(i = 0; i < maxnums; i++) {
printf("enter a number, or nondigit to quit: ");
fflush(stdout);
double x;
if(scanf("%lf", &x) != 1)
break;
numbers[i] = x;
}
int nnum = i;
printf("you typed %d number(s):\n", nnum);
for(i = 0; i < nnum; i++)
printf("%d: %f\n", i, numbers[i]);
}
The loop stops (using the break statement; I hope you've gotten to that in class by now) if scanf returns something other than 1, indicating that no number could be read. The loop also stops after the user enters 10 numbers, because that's how big the input array is.
It looks like the loop reads only floating-point numbers, and in a sense it does, but if the user types a pure integer, like 123, without a decimal point, that's still perfectly acceptable as a floating-point input, and it will be read as the floating-point value 123.000.
On the other hand, if there was a requirement to be able to tell whether the user actually entered a pure integer versus a floating-point number, or if there was a requirement to do something else with the pure integers other than storing them in the same array with the floating-point inputs, or if there was a requirement to know (to read and perhaps process) the specific non-numeric input the user typed to terminate the input loop, none of those additional requirements could be met with this simple code. In fact, in my opinion, meeting any of those additional requirements using scanf is effectively impossible, and some completely different approach, not involving scanf, would be required.
... to check if user input is a float/integer or a letter ...
scanf() is a weak function to use when input is either convertable as a float, integer or character - yet OP reports scanf() is obliged. Requirement to use scanf() is misguided.
First read a line of user input into a string. Be sure to limit input width.
char line[100 + 1];
if (scanf(" %100[^\n]", line) == 1) {
// Successfully read a line
Now process the string. Use strtof(), strtoll() to parse for float, integer. Test the endptr for conversion success.
char *endptr; // Record end of conversion.
errno = 0;
long long ll = strtoll(line, &endptr, 10);
if (endptr > line && errno == 0 && *endptr == 0) {
// Successfully parsed a long int
printf("long long: %ld\n", ll);
} else {
errno = 0;
float f = strtof(line, &endptr);
if (endptr > line && *endptr == 0) {
// Successfully parsed a float
printf("float: %.9g\n", f);
} else {
printf("otherwise <%s>\n", line);
}
}
Additional code useful to detect empty or long lines.
After any selection, I want to ask the user if they want to use the program again, or quit. But if y is inputted code doesn't work properly again. I tried the other solutions like clearing memory etc but I am not very experienced so I don't know what I am doing. Also sorry about my language. This is a part of my code. I have 13 different selections each of them work the same
char str[100];
int selection;
char selection2;
int i;
begin:
printf("Welcome to the Character/String Specification program\n");
printf("Please enter whatever you want \n");
scanf(" %s", str);
printf("\nSelect the specification you want\n");
printf("1) is your input a letter?\n");
printf("2) is your input a whitespace?\n");
printf("3) is your input a decimal digit?\n");
printf("4) is your input a hexadecimal digit?\n");
printf("5) is your input an upper-case letter?\n");
printf("6) is your input a lower-case letter?\n");
printf("7) is your input a letter or a decimal digit?\n");
printf("8) is your input a control character?(ACSII 0..31 and 127)\n");
printf("9) is your input a not a letter, digit, whitespace, or invisible control character?\n");
printf("10)is your input a printable (ASCIII ' '..'~')\n");
printf("11)is your input have a graphical representation\n");
printf("12)Do you want to see your input as all upper characters?\n");
printf("13)Do you want to see your input as all lower characters?\n\n");
scanf(" %d",&selection);
printf("\n");
while(true)
{
if(selection == 1)
{
while(str[i])
{
if(isalpha(str[i]))
{
printf("%c is an alphabet\n",str[i]);
}
else
{
printf("%c is not an alphabet\n",str[i]);
}
i++;
}
printf("Do you want to go back to the start point? (y) for yes,(n) for no\n");
scanf(" %c",&selection2);
if(selection2=='y')
{
goto begin;
}
else if(selection2=='n')
{
printf("Goodbye\n");
break;
}
instead of using goto, I would do something like this:
int value = 1;
do {
//enter your code here
if(selection2=='n')
{
printf("Goodbye\n");
value = 0;
break;
}
} while(value)
This will cause the code to run at least once and continue running based on user input.
Goto is not the best practice as it makes it harder to read.
I've set up a script that asks the user to input a number that's two digits long at most.
But if the user types three non-integers in, like 'fff', the recursive function promptGetAge() fires infinitely.
Why?
int promptGetAge(){
char myString[3];
cout<<"How old is your dog? ";
cin.getline(myString,3,'\n');
int userStringToInt = atoi(myString);
if(userStringToInt==0 && !(myString=="0\0")){
promptGetAge();
} else {
return userStringToInt;
}
}
int main(){
cout<<"Your dog is "<<promptGetAge()<<" years old!"<<endl;
return 0;
}
Use the strcmp() function in <cstring> to compare content of strings, not == (which compares only the address of the first character). i.e. instead of myString == "0\0" use strcmp(myString, "0") == 0.
Or, better yet, use the string type in <string>. Then you can use == for comparison.
Note that string literals have a '\0' character appended anyway, and strcmp() searches for the first one it finds. So there is no functional difference between strcmp(myString, "0") and strcmp(myString, "0\0")
And don't use recursion to go back and repeat an action. Use a loop.
When I run this, the if statement is supposed to compare only the first element of both arrays. It works fine as long as array "ans" only contains y or Y, but if I enter a "yes", etc, it comes back false and shoots down to else.
char y[2]= "y";
char n[2] = "n";
char ans[5];
printf("Answer yes of no. (y/n) ");
scanf(" %s", ans);
if (strcasecmp(&ans[0], &y[0]) == 0)
{
printf("You said yes.\n");
printf("%c, %s\n", y[0], ans);
}
else if (strcasecmp(&ans[0], &n[0]) == 0)
{
printf("You said no.\n");
}
else
{
printf("hmm?\n");
}
Not really, strcasecmp() compares two strings, not two characters, even if you pass it the pointer to their first characters, it still compare two strings that start from this character until a terminating '\0'.
You can compare their first characters ignoring case like this:
if (toupper(ans[0]) == toupper(y[0])))
Use strncasecmp instead of strcasecmp, so that you can compare just the first character rather than the entire string. Change:
if (strcasecmp(&ans[0], &y[0]) == 0)
to:
if (strncasecmp(ans, y, 1) == 0)
and similarly for the rest.
I am working on program where a list of options is displayed to the user and he would then enter an integer to specify which option he wants to select.Now I have pre-empted the situation where the user might enter an integer value apart from the valid ones. But if he enters any other value, say a character or a string, the program goes into an infinite loop with the list of options being printed infinitely. How can i rectify this? I mean, I should be able to give my user an error when for a predefined integer variable he enters a value that is not an integer.
Any help appreciated. Here is a sample code.
do{
printf("Select appropriate option.\n");
printf("Press 1 to do this");
printf("Press 2 to do that.\n");
printf("Press 3 to exit the program.\n");
scanf("%d",&choice);
if(choice!=1 && choice!=2 && choice!=3)
printf("You entered an invalid choice. Please enter again.\n");
switch(choice){
case 1:
//do this
break
case 2:
//do that
break;
case 3:
exit(1);
}}
while(choice!=3);
So basically when a user enters a non-integer value for choice I want the program to notify the user and ask him for another input.
It cannot be done with direct scanf into an integer variable. Such scanf will not only accept 1.23, it will also accept 1abcde and other inputs. scanf (and other conversion functions) reads as much as it can in accordance with the requested format. It stops when it finds something that does not satisfy format requirements and simply leaves it untouched.
If you want to perform this sort of analysis, you have to read the input as string and then parse and analyze that string manually.
A C-style code sketch (since you insist on C-style code, despite having tagged it as [C++]) might look as follows
char buffer[100]; /* 100 should be enough for everyone :) */
int n = scanf("%s", buffer);
if (n < 1)
/* ERROR, can't read */;
char *end;
long choice = strtol(buffer, &end, 10);
if (end == buffer || *end != '\0' || errno == ERANGE)
/* ERROR, bad format */;
/* ... */
scanf will not consume any non-digits when converting %d. It will return 0 because it didn't convert anything, and the "bad input" will still be there waiting to be consumed. You have to consume it in some way to be ready for a valid input.
(also note you're excluding 3 in your if before testing for it in your switch)
Use iostream - see http://www.cplusplus.com/reference/iostream/
Having said that if you insist on using scanf - check the return value - i.e. read http://linux.die.net/man/3/scanf
isdigit will check for any input that is a digit(number) type.
For this include header ctype.h.
Also terminate your program using exit(0) if input is incorrect.
For this include header stdlib.h.
#include<ctype.h>
#include<stdlib.h>
char c;
scanf("%c", &c);
if (isdigit(c))
{
case statement...
...
...
}
else
{
printf("Wrong input");
exit(0);
}