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.
Related
This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 5 months ago.
I'm new to C and I'm building a quiz game, every time you answer right your score gets higher, however there is a bug that i was not able to find which is even if you answer correctly the code will tell you that you are wrong and moves to the next question in the end you will always get a score of 0/3.
my question is what is the reason that is preventing my code from determining that the answer is right, why does it always go to the else statement which is wrong.
this is the code
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char questions[][100] = {
"\n1. what company was the first to create a foldable phone? ",
"\n2. what company was the first to create a foldable laptop? ",
"\n3. what company was the first to create a full electric car? "
};
char options[][100] = {
"\nA. apple, B. oppo, C. samsung, D. motorolla",
"\nA. Asus, B. MSI, C. Microsoft, D. Gygabyte",
"\nA. mazda, B. chevrollet, C. toyota, D. Tesla"
};
char answers[] = {'C', 'A', 'D'};
int score = 0;
char ans;
for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++)
{
printf("%s", questions[i]);
printf("%s", options[i]);
printf("\n\nwhat is your answer? ");
scanf("%c", &ans);
scanf("%c");
ans = toupper(ans);
if (ans == answers[i])
{
score += 1;
printf("\nthat's right!");
printf("\nnext question\n");
}
else
{
printf("\nwrong!");
printf("\nnext question\n");
}
}
printf("\n\nthe correct answers are: ");
for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++)
{
printf("%c ", answers[i]);
}
printf("\nyour score is: %d/3", score);
}
ans is the user guess.
if anyone have the solution for this i would really appreciate it.
thanks in advance.
ok , so you have only one problem in your code and a warning .
in these 2 lines :
scanf("%c", &ans);
scanf("%c");
when the user enter a char like a and press enter , the first scanf will get a successfully but the second scanf("%c"); is incorrect as you are telling the function to get a character from the input and store it but where ? , it gave me undefined behavior .
note that , in order to clear the buffer after reading one char , you can simply write instead of the above 2 lines , these lines :
scanf("%c", &ans);
fgets(dummy, sizeof(dummy), stdin);
where fgets(dummy, 20, stdin); will read any chars there in the buffer so as to clear it.
also there is a warning in this line ans = toupper(ans); as the warning in my compiler says :
Clang-Tidy: Narrowing conversion from 'int' to signed type 'char' is implementation-defined
as the function called toupper takes int and returns int but you are storing the result into a char , so either cast the result as ans = (char)toupper(ans); or you can use _toupper which takes char and returns char like ans = _toupper(ans);
and this is the full code with these only 2 edits :
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char questions[][100] = {"\n1. what company was the first to create a foldable phone? ",
"\n2. what company was the first to create a foldable laptop? ",
"\n3. what company was the first to create a full electric car? "};
char options[][100] = {"\nA. apple, B. oppo, C. samsung, D. motorolla",
"\nA. Asus, B. MSI, C. Microsoft, D. Gygabyte",
"\nA. mazda, B. chevrollet, C. toyota, D. Tesla"};
char answers[] = {'C', 'A', 'D'};
int score = 0;
char ans, dummy[20];
for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++)
{
printf("%s", questions[i]);
printf("%s", options[i]);
printf("\n\nwhat is your answer? ");
scanf("%c", &ans);
fgets(dummy, sizeof(dummy), stdin);
ans = _toupper(ans);
if (ans == answers[i])
{
score += 1;
printf("\nthat's right!");
printf("\nnext question\n");
}
else
{
printf("\nwrong!");
printf("\nnext question\n");
}
}
printf("\n\nthe correct answers are: ");
for (int i = 0; i < sizeof(questions) / sizeof(questions[0]); i++)
{
printf("%c ", answers[i]);
}
printf("\nyour score is: %d/3", score);
}
and this is the output :
1. what company was the first to create a foldable phone?
A. apple, B. oppo, C. samsung, D. motorolla
what is your answer?c
that's right!
next question
2. what company was the first to create a foldable laptop?
A. Asus, B. MSI, C. Microsoft, D. Gygabyte
what is your answer?a
that's right!
next question
3. what company was the first to create a full electric car?
A. mazda, B. chevrollet, C. toyota, D. Tesla
what is your answer?d
that's right!
next question
the correct answers are: C A D
your score is: 3/3
Process finished with exit code 0
probably another dumb error but I really can't wrap my head around this.
I'm writing a basic polynomials class, and my program suddenly crashes upon input of a couple of ints.. I tried searching for a solution but I couldn't find one :/
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Homework.h"
#include "Fraction.h"
int main()
{
//Input from user
int degree, i;
printf("Insert the degree of the polynomomial: \n");
scanf("%d", °ree);
//Get the coefficcients
struct fraction *bucket = malloc((sizeof(struct fraction))*(degree + 1));
int num;
unsigned int den;
for(i = 0; i < degree + 1; i++)
{
num = 0;
den = 1;
printf("Insert the coefficcient of degree %d, first num and afterwards
the den \n", i);
printf("Numerator:\n");
if(scanf("%d", &num) != 1)
printf("Input error\n");
printf("Denominator:\n");
if(scanf("%u", &den) != 1)
printf("Input error\n");
//struct fraction temp = {num, den};
//memcpy(&bucket[0], &temp, sizeof(struct fraction));
}
//Check insertion
printf("Test\n");
//print_fraction(bucket[0]);
}
The program exits even before printing "Test", and to input I am using input number + enter key.
Thanks very much for any help!
Proof it compiles
Your code seems to be working fine.
The only changes i've made in order to compile it was to comment out the line where you are using malloc, and also brought your print statement on one line.
If you are using a newer version of Visual Studio then it will give you issues when using the scanf function. You either have to use scanf_s or disable the warning with this line at the top:
#pragma warning(disable: 4996)
Hope this helps.
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! :)
for our homework we have to compile the program we wrote in the school. I have typed it without mistakes(verified with my colleagues) and the program does not work, I am using DEV C++ and the error log says, file not recognized: File format not recognized.
I tried using integer and not double but it stays the same...I have no idea what is wrong.
#include <stdio.h>
#define VELIKOST 23
int main (void)
{
double dPolje[VELIKOST];
int iStevec,iVecje=0;
printf("Algoritem, ki določi koliko elementov podatkovnega polja imajo vrednosti vecje ali enake od 10 \r\n");
for(iStevec=0;iStevec<VELIKOST;iStevec++)
{
printf("Vnesite %i. stevilo:",iStevec=iStevec+1);
fflush(stdin);
scanf("%lf",&dPolje[iStevec]);
if(dPolje[VELIKOST]>=10)
{
iVecje++;
printf("Element dPolje [%i]=%f.",iStevec,dPolje[iStevec]);
}
printf("%i elementov polja je imelo vecje ali enako vredost 10.",iVecje);
return(0);
}
}
I'm guessing that Dev C++ doesn't support Slovenian.
Create a new file and try this code:
#include <stdio.h>
#define SIZE 23
int main(){
double dField[SIZE];
int i, larger = 0;
printf("This algorithm, determines how many data field items have values greater than or equal to 10.\n");
for (i = 0; i < SIZE; i++){
printf("Enter field number %i:", i + 1); //Note I fixed this original code had i = i + 1
//fflush(stdin); unneeded
scanf("%lf", &dField[i]);
if (dField[i] >= 10){
larger++;
printf("Field number %i = %lf", i, dField[i]);
}
} //Moved this above final output and return
printf("%i field items were greater than or equal to 10 ", larger);
return 0;
}
I expect that to work.
Either way I'd definitely change compilers. Visual Studio Community Is a great fully featured IDE.
I have a problem writing code which does the following: declare a struct{char c; int x; } array and load it with scanf via a loop. After it's loaded, a call to function f will be made which will replace every occurrence of digits in the struct's component c with 0, and will return the sum of the digits replaced by zero.
Code and output are below and I have problem that the loop in the function f seems to iterate one time, and it gives out some really weird values.
This is an exam question so I have to use printf, scanf etc. Also I have that exam in an hour so any quick help is appreciated :)
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 2
struct par {
char c;
int x;
};
int f(struct par *niz) {
int i;
int n=0;
for(i=0; i<MAX; i++) {
if(isdigit(niz[i].c)) {
niz[i].c = niz[i].c-'0';
printf("niz[i].c = %d\n i = %d", niz[i].c, i);
n=n+niz[i].c;
niz[i].c='0';
}
}
return n;
}
void main() {
int n;
int i;
struct par niz[MAX];
printf("enter\n");
for(i=0; i<MAX; i++) {
scanf("%c", &niz[i].c);
scanf("%d", &niz[i].x);
}
n=f(niz);
for(int i=0; i<MAX; i++) {
printf("%d\n", niz[i].c);
printf("%d\n", niz[i].x);
}
printf("n = %d\n", n);
}
OUTPUT:
enter
2
2
2
niz[i].c = 2
i = 048
2
10
2
n = 2
When you press enter after the first input, the newline is not scanned by scanf and is left in the input buffer. When you then try to read the number scanf sees the newline and not a number so doesn't scan anything.
The simple solution to that is to add a leading space in front of the formats:
scanf(" %c", &niz[i].c);
scanf(" %d", &niz[i].x);
/* ^ */
This tells scanf to skip whitespace.
Use
niz[i].c = getchar();
instead of
scanf("%c", &niz[i].c);
or, you can use other better methods for getting char input discussed at SO,
Now,
You see second time you provided input only once, that is because the Enter you pressed after giving 2 as input to first char remained in input buffer, and was read on second iteration.
You are getting 10 as output, because, it is ASCII for \r, the Enter. It is not a digit, so not replaced to be '0'.
I am looking at your code (i am not using console for a decade, but ) here are some insights:
try to rename MAX with something else
do not know your IDE but sometimes MAX is reserved
and using it as macro can cause problems on some compilers
change scanf("%c", &niz[i].c) to scanf("%c", &(niz[i].c))
just to be shore that correct adsress is send to scanf
change scanf("%d", &niz[i].x) to scanf("%i", &(niz[i].x))
change "%d" to the correct value (this is main your problem)
"%c" for char
"%i" for int
Try to trace line by line and watch for improper variables change if above points does not help
weird values?
because you forgot "\n" after the line, so next print is behind the line "i = %d".
And, check return value of every function except ones that return void.