I started learning C language yesterday and made a simple binary coverter. It works fine on my PC, however, it doesn't work on most online code runners(compilers) except for could9. It looks like the scanf function are not compatible with online IDE in general?
Here's the code.
#include <stdio.h>
#include <string.h>
int main(){
int a;
int b;
int c[255];
char opt[100];
printf("10進数の値を入力してください > ");
scanf("%d", &a);
printf("計算式を表示しますか? y(yes) or n(no) > ");
scanf("%s", opt);
if(strcmp(opt, "y") == 0){
printf("\n計算式: \n");
}
int i = 0;
while(a > 0){
b = a / 2;
c[i] = a % 2;
if(strcmp(opt, "y") == 0){
printf("%d ÷ 2 = %d 余り %d\n", a, b, c[i]);
}
a = b;
i++;
}
printf("\n2進数: ");
int j;
for(j = i-1; j >= 0; j--){
printf("%d", c[j]);
}
printf("\n");
return 0;
}
Any advice will be much appreciated.
My psychic powers tell me you are expecting these online compilers to prompt you for input (like running the program in a terminal window). Unfortunately, this is not the case for most online compilers. Instead, there is a text box somewhere where you type in all of the input that you want in your program's standard input.
For example, take this small program:
#include <stdio.h>
int main()
{
char c;
printf("Gimme a character! ");
fflush(stdout);
scanf(" %c", &c);
printf("You typed in '%c'! Yay! :)\n", c);
}
Compiling and running this in a terminal could produce the following in the window (input is in bold):
Gimme a character! f
You typed in 'f'! Yay! :)
But running this in an online compiler that doesn't prompt you for input could look like this:
Gimme a character! You typed in ' '! Yay! :)
By typing input into the text box provided (where it is depends on the online compiler) you can give input to the program that way.
STDIN:
f
Output:
Gimme a character! You typed in 'f'! Yay! :)
Related
#include <stdio.h>
int main(int argc, char** argv)
{
int n;
int numbers;
int i=0;
int sum=0;
double average;
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
sum = sum +numbers;
i++;
}
average = sum/n;
printf("\nSum of the %d Numbers = %d",n, sum);
printf("\nAverage of the %d Numbers = %.2f",n, average);
return 0;
}
i get the output "exited, floating point exception"
im not sure how to fix it.
i found online to add before the while loop
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
but i dont want that there
Hint: you want the user to be able to signal to your application that they finished entering the elements. So you'd start with n=0 and then increment it each time the user provides a new element, and exit the loop when the user does "something" that you can detect.
For starters, let's say that the user closes the input by pressing Ctrl-Z on Windows, or Ctrl-D on Unix. The input will fail with EOF then - scanf() won't return 1 anymore. So you can check for this:
#include <stdio.h>
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf("%d", &number);
if (result == 1) break;
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
But this also ends the input when anything non-numeric is entered. Due to how scanf() is designed, you need to do something else to skip invalid input - usually by consuming input character-by-character until an end of line is reached. Thus, the variant that would not stop with invalid input, but allow the user another chance, needs to differentiate between scanf() returning EOF vs it returning 0 (invalid input):
#include <stdio.h>
void skip_input_till_next_line(void)
{
for (;;) {
char c;
if (scanf("%c", &c) != 1) break;
if (c == '\n') break;
}
}
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf(" %d", &number);
if (result == EOF) break;
if (result != 1) {
// We've got something that is not a number
fprintf(stderr, "Invalid input. Please try again.\n");
skip_input_till_next_line();
continue;
}
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
As a learner I'd recommend you to think about the pseudo code rather than the actual code.
Answers above are really good. I just want to add few things:
As a programmer you've to teach the hardware what you want it to do. Think:
Have you told your program how many numbers it takes as input? Is it limited or unlimited?
How will your program knows when to stop taking inputs?
I hope you agree that (sum n)/n would throw an error if user
doesn't enter anything or only enters 0?
What will happen if User enters characters instead?
Another important thing is that you need to clearly specify why you don't want to do certain thing in your code? This might help us understand better what are the limitations.
If you think about these things before and ask questions you'll learn better. Community is here to help you.
I'm doing an exercise to print 3 letters taken from the user. The first two letters end up fine, but the last one is always the letter that comes after what the user inputs for some reason (I've tried a few different combinations of inputs and it's always the same result):
#include <stdio.h>
int main(){
char userChar[3];
int i;
for (i = 1; i <= 3; i++){
printf("Enter letter %d\n", i);
scanf(" %c", &userChar[i]);
}
printf("%c %c %c", userChar[1], userChar[2], userChar[3]);
return 0;
}
The input is: abc
The output is: abd
What did I screw up? Thanks for your help!
Edit made recommended changes but still not working
I'll post this as an answer just to clarify the amendments
#include <stdio.h>
int main(){
char userChar[3];
int i;
for (i = 0; i < 3; i++){ // the loop range
printf("Enter letter %d\n", i + 1); // for human use
scanf(" %c", &userChar[i]);
}
printf("%c %c %c", userChar[0], userChar[1], userChar[2]); // the array indexing
return 0;
}
Program session
Enter letter 1
a
Enter letter 2
b
Enter letter 3
c
a b c
I am able to write a program to find the mode provided there is only one mode. However, I'm not sure how to alter my code so it can function properly when there is more than one mode.
Here is what I have! Any advice on how to fix my code would be appreciated.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main ()
{
int x, i, c[101], mode;
printf("please enter test scores between 0 and 100\n");
i = 0;
mode = 0;
while (i<=100)
{
c[i]=0;
i=i+1;
}
scanf("%d", &x);
while ((x>=0) && (x<=100))
{
c[x]=c[x]+1;
if (c[x]>=mode)
{mode=x;}
scanf("%d", &x);
}
printf("the mode is %d\n", mode);
}
You'd want to:
a) Have something that keeps track of how often each value occurred. You're already using an array of "occurrence counts" for this.
b) Find the highest "occurrence count"
c) Find all values that share the highest "occurrence count"
For your code, this can mostly be done by replacing:
if (c[x]>=mode)
{mode=x;}
..with something more like:
if (c[x] > highest)
{highest = c[x];}
..and then doing something like this at the end:
printf("the mode/s are:");
for(i = 0; i <= 100; i++) {
if(c[i] == highest) {
printf(" %d", i);
}
}
printf("\n");
Since, i am kinda very new to C-language I have to build a program which work user-friendly. Like user will give instructions of i need A to Z alphabets and after execute he will get result by using while condition. Is that possible ?.
#include <stdio.h>
int main()
char c;
for(c='A'; c<='Z'; ++c)
printf("%c ",c);
return 0;
}
Like that if I can write it using hard coded values, What if I have to give input From which Alphabet to Alphabet you want result and it give result till user want using while loop.
#include <stdio.h>
int main()
{
char c;
char b;
printf("Enter the first letter\n");
c=getchar();
getchar();
printf("Enter the last letter\n");
b=getchar();
getchar();
for ( ;c<=b; ++c)
{
printf("%c", c);
}
return 0;
}
I'm relatively new to C programming, its my 6th week in class so far i haven't had any major issues. I just cant figure out were i'm going wrong with my current assignment and its due in just a couple hours. Here is what i have so far. i'm using visual studio 2012.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char textChar;
int textLenght = 0;
int asciiArray[128] = {0};
int i;
int main()
{
printf("Enter a line of text: ");
scanf("%d", &textChar);
while ((textChar = getchar())!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
printf("\nFREQUENCY TABLE\n");
printf("---------------\n");
printf("Char Count %% of Total\n");
printf("---- ----- ----------\n");
printf(" ALL %5d %9.2f%%\n", textLenght,( textLenght * 100.0 ) / textLenght );
for (i = 0; i < 128; i++)
if( asciiArray[textChar] != 0 )
printf("%c %d %9.2f%% \n",i+ "0",asciiArray[textChar]);
getchar();
getchar();
return 0;
}
Now i know there is a problem within my for loop because its not displaying, I'm just not sure if there are other problems besides that. Any help is greatly appreciated thanks in advance.
This line is not right.
scanf("%d", &textChar);
It's not clear to me what you are trying to accomplish with this line.
When you use %d as the format specifier, the function will try to read an integer and store it at the given address. Since type of textChar is not int, you are going to run into undefined behavior right away.
Instead of using getchar, which is not a standard C library function, you should use fgetc(stdin).
fgetc() returns an int. Make sure to change the type of textChar to int.
Change the lines:
printf("Enter a line of text: ");
scanf("%d", &textChar);
while ((textChar = getchar())!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
to
printf("Enter a line of text: ");
while ((textChar = fgetc(stdin))!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
I would remove the last two calls to getchar(). They don't seem to serve any purpose.