Take Float Input in a Row With Tabs
I want to take float input from the user a specific number of times in such a way that when the user presses the enter key, instead of going to the next line as scanf() automatically does, move the cursor one tab forward (\t).
Example:
5 -4 8 75
2 -7 4 11
Note: I'm using this code to get float values into an array for matrices.
I have tried a variation of the following:-
int i=0,interval=10;
float a[10]={0};
for (i=0;i<interval;i++)
{
scanf("%f",a[i]);
printf("\t");
i++;
}
OR
int i=0;
float a[10]={0};
while (a[i]=getche()!='\r')
{
printf("\t");
i++;
}
I would really appreciate it if someone helps me out.
If you were using windows, you can actually try:
#include <conio.h>
and:
char c[100];
int i = 0;
float f;
while ((c[i++]=getch())!='\t');
c[i++] = '\0';
f = atof(c);
Since getch() read characters instantly.
Related
This question already has answers here:
Program doesn't wait for user input with scanf("%c",&yn);
(5 answers)
scanf() leaves the newline character in the buffer
(7 answers)
Closed 13 days ago.
I am writing a simple converter to convert 3 metric measurements to British system values.I am supposed to write functions to solve it.
Below is the code I wrote.
#include <stdio.h>
void meter_to_feet(double,double);
void gram_to_pounds(double,double);
double Cel_to_Fahrenheit(double);
double target;
char letter;
int main(void){
printf("How many values to convert? ");
int time;
scanf("%d",&time);
//printf("%d\n",time);
for (int i=0;i<time;i++){
scanf("%lf",&target); //problem occurs here
scanf("%c",&letter); //and here
if('m'==letter){
meter_to_feet(target,3.2808);
}else if('g'==letter){
gram_to_pounds(target,0.002205);
}else if('c'==letter){
Cel_to_Fahrenheit(target);
}
}
return 0;
}
void meter_to_feet(double x,double y){
double r1;
r1=x*y;
printf("%0.6f ft\n",r1);
}
void gram_to_pounds(double x,double y){
double r1;
r1=x*y;
printf("%0.6f lbs\n",r1);
}
double Cel_to_Fahrenheit(double x){
double r1;
r1=x*1.8+32;
printf("%0.6f f\n",r1);
return r1;
}
I give it a .txt file looks like below to test this code in a step-by-step terminal and it passed.
4
12 m
14.2 g
3.2 c
19 g
However, when I complie and run above code using clang, I only get results of first two metric measurements--12m and 14.2g. It omitted the last two for some reason. I figured that I have to change my two scanf() lines into scanf("%lf %c",&target,&letter);in order to get desired output.
I wonder how exactly scanf() here, treats input in such scenario?
Why is this code not running after printing of array if I take value of n>=9?
#include <stdio.h>
#include <math.h>
float mean_function(float array[],int n);
int main() {
int i,n;
float array[n],mean,sum=0,s2,summation,deno,C[i],elements;
printf("Enter No of Elements\n");
scanf("%d",&n);
printf("Enter Elements\n");
for(i=0;i<n;i++){
scanf("%f",&array[i]);
printf("%f",array[i]);
}
printf("sample variance(s2) : (sum((x-mean)*(x-mean)))/(n-1) /n");
printf("population variance(sigma2) : (sum((x-u)*(x-u))/n");
mean_function(array,n);
for(i=0;i<n;i++) {
deno=((array[i]-mean)*(array[i]-mean));
C[i]=deno;
summation=summation+C[i];
}
s2=((summation)/(n-1));
printf("s2=%f \n",s2);
}
float mean_function(float array[],int n) {
int i;
float sum=0,mean;
for(i=0;i<n;i++){ sum=sum+array[i]; }
mean=(sum/n);
return mean;
}
Why is this code not running after printing of array if I take value
of n>=9?
Some thoughts about your code (and about building programs in steps):
Arrays in C don't change in size once defined. VLAs are out for a variety of reasons. malloc() is in.
Use double, unless there is a specific reason to use floats.
Define and initialize one variable per line. Uninit vars can only result in an error as mentioned by #Jens.
Function declarations at the top (which you have done)
During development, there is no need to complicate things with a scanf (at least initially). It only adds an unwarranted layer of complexity. If you are testing statistical functions (mean, variance), put numbers in a pre-defined static array and verify functionality first.
C[i] as been declared with uninitialized i.
For this initial phase of building this program, I include a basic program.
I am not a fan of zero space between tokens (but ignore that)
Consider calling your array something other than 'array'.
Calculating the size of the samples array allows you to change the number of elements without changing anything else in code; which adds another layer of complexity to an already difficult phase.
#include <stdio.h>
#include <math.h>
double sample_mean(double* p, int n);
int main()
{
double samples[] = {1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 16.5, 2.3};
double mean = 0.0;
int size_samples = sizeof samples/sizeof(double);
printf("size_samples = %d\n", size_samples);
mean = sample_mean(samples, size_samples);
printf("Mean = %.2lf", mean);
}
// -------------------------------
double sample_mean(double* p, int n)
{
double mean = 0.0;
double total = 0.0;
for(int i = 0; i < n; i++)
total += *p++;
mean = total/n;
return mean;
}
Once this functionality is present (saved), you can start working on other stat functions. This way you can work step by step to get closer to the desired outcome.
Next up you can define sample_variance(double* p, int n) and work on that knowing that additional(new errors) are not coming from your code written so far.
Output:
size_samples = 8
Mean = 5.24
I hope it helps.
The code is likely not running because array[n] is declared with an uninitialized n. At the time you read n with scanf(), the array does not automatically "grow into the right size". You should either declare array big enough, or if you really want it to be user-defined, use malloc to allocate it (read the comp.lang.c FAQ) and all Stackoverflow questions tagged array...)
In addition, the scanf at some point fails. Note that when you enter numbers, you also have the "Enter" as a newline ('\n') in the input stream. You never read the newline so the next scanf fails.
This becomes obvious when you actually check the return value from scanf with code like this:
if (scanf("%f", &array[i]) == 1) {
/* successfully converted 1 item */
}
else {
/* scanf failed */
}
Usually what you want is to skip whitespace in the input. You do this by placing a space in the scanf format. Note that a single space tells scanf to skip any amount of white-space.
if (scanf(" %f", &array[i]) == 1) {
The text file contains 52 lines that are in the format:
A .013420
B .000191
C .011222
...
I want to ignore the letters and I need to extract the values from the file and store the first 26 in one array which I named freqOne[] and store the last 26 values in another array named freqTwo[]. I will later use these values for calculations.
here is my attempt:
#include <stdio.h>
#include <stdlib.h>
int main (){
FILE *input1;
/*char freqOne[26]; i use these arrays for attempt 1
char freqTwo[26];*/
double freqOne[26];
double freqTwo[26];
input1 = fopen("test8.txt", "r");
if(input1 == NULL){
perror("test8.txt");
exit(EXIT_FAILURE);
}
/* attempt one: all the values print out correctly but idk how to use them :(*/
/*while(fgets(freqOne, sizeof(freqOne), input1)){
printf("%s", freqOne);
}
while(fgets(freqTwo, sizeof(freqTwo), input1)){
printf("%s", freqTwo);
}
*/
/*fclose(input1); */
int h;
int i;
/* another attempt i made, this one prints out the a large negative number for every element :(*/
for(i=0; i<26; i++){
fscanf(input1,"%lf", &freqOne[i]);
printf("%lf\n", freqOne[i]);
}
for(h=0;h<26; h++){
fscanf(input1,"%lf", &freqTwo[h]);
printf("%lf\n", freqTwo[h]);
}
fclose(input1);
/*a = (freqOne[0]-freqTwo[0])*(freqOne[0]-freqTwo[0]);
printf("%lf", a);*/
}
In my first attempt, i was able to print out all the values correctly, but I am not sure how to use them. I printed them out as strings, but when I try to print them out as %lf, it gave me 0's for every value.
In my second attempt, I did some googling and found that I should try the fscanf function, but this did not work for either and a large negative number was printed out for every value. I am pretty stuck right now and out of ideas.
So OP can close this post:
To ignore the A,B,C, etc., use assignment suppression '*'
// fscanf(input1,"%lf", &freqOne[i]);
fscanf(input1,"%*s %lf", &freqOne[i]);
Always a good idea to check I/O function results:
if (fscanf(input1,"%*s %lf", &freqOne[i]) != 1) Handle_Unexpected_Input();
OK, so my task is to get a single digit from a natural number and sum the square numbers (Using function while, which means no arrays yet :S). For instance I type 123 so sum=1*100+2*10+3*1; However the problem is that the digit could be whatever. My problem is that the power rises with int but its like so - 1, 10, 99, 1000. The problem for me is 99. Also answer is looping but I'll fix it later. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int N,
number=0,
answer=0,
a=1,
i=0;
printf("Type natural number: ");
scanf("%d",&N);
while(N>i)
{
number=N%10;
N/=10;
a=10;
a=pow(a,i);
answer+=number*number*a;
printf("%d\n", answer);
i++;
}
return 0;
}
Try it the other way around. Don't make the input an integer. Start at the beginning of the stream, get the character, convert it to an int 'number'. Then do
answer = 10 * answer;
answer += (number * number);
This will build up your answer little by little. Note that I am not sure that this is what you are asking for due to your example not seeming to match the code.
Let me know if this is off-base and I will update it.
My teacher gave an assignment to me. The question is below:=
Write a program that prompts the user to enter 10 double numbers. The program should accomplish the follwing:
a. Store the information in a 10-element array.
b. Display the 10 numbers back to the user.
I could do all of the above in main().
Hint: You should use loops, not hardcode the values 0 through 9. It should be easy to convert your program to accept 1000 numbers instead of 10.
For a bonus mark, do at least one of the tasks (a or b) in a separate function. Pass the array to the function; do NOT use global (extern) variables.
I confused above. I wrote a program in the source code. Am I doing wrong? It is below:=
#include<stdio.h>
int main(void)
{
int number[10];
int i;
for (i = 0; i <10; i++)
printf("%d.\n", i, number[i]);
printf("\n\nPress [Enter] to exit program.\n");
fflush(stdin);
getchar();
return 0;
}
Thanks.
Not too bad so far, I'd like to make the following comments:
if you need to input double numbers, you should probably use double rather than int.
you need a statement (maybe in your current loop but possibly in another loop preceding the current one) which inputs the numbers. Look into scanf for this.
Using %d with printf is for integers, not doubles. You will have hopefully already figured out the format string to used when you looked into scanf above.
Bravo for using the correct int main(void) form and for not including conio.h :-)
Once you've figured those bits out, then you can worry about doing it in a separate function.
Based on the code you have given above, I would suggest reading up on the following:
scanf
functions in C, particularly passing arrays to functions: this link should be good.
Note to OP: If you were able to do (a) and (b) in main(), the code above is not complete. It would be nice the functions you created for getting (a) and (b) above done for getting to the root of your "confusion".
Let me know in case you need more help.
HTH,
Sriram
Try this it may sloves your problem.
#include<stdio.h>
int main(void)
{
double number[10];
int i;
printf("Enter double numbers:");
for (i = 0; i <10; i++)
scanf("%lf",&number[i] );
printf("The numbers you entered are:");
for (i = 0; i <10; i++)
printf("%lf\n",number[i] );
return 0;
}