How can i stop this program by giving some input? - c

I was trying to filter out integers from input, without using getchar() function,
To be exact, i was trying to read coefficients and powers from 1x^2 + 3x^6 + 5x^0, that's when i ended up writing this program, it is not complete program, it was supposed to be a part of program .
int main(){
int a , b, i = 0, n;
char c[2];
while(5){
if(scanf("%1s", c) == 1){
if( (n = atoi(c)) != 0 || (*c == 48) ){
printf("%d", n);
}
}
}
return 0;
}
so what is correct way of doing it?
what are some modifications?
thanks :)

if this 1x^2 + 3x^6 + 5x^0 is your exact input, you can use scanf to scan it.
int powers[3];
int coefficients[3];
if (scanf("%dx^%d + %dx^%d + %dx^%d", &coefficients[0], &powers[0], &coefficients[1], &powers[1], &coefficients[2], &powers[2]) != 6)
{
exit(EXIT_FAILURE);
}

Related

Why does my conversion method in C continue to fail?

I am trying to convert from a popen pass, to a float as the final result. I have tried converting to a char, and then into a float in every possible way I can find, however the output I have seen using printf seems to be wrong every time. I have tried using a tostring function, as well as using a %s like in the printf function that returns the correct function, however it all seems to give me the wrong output as soon as I try to convert the output. Should I be trying a different conversion method?
Here is the code.
FILE * uname;
char os[80];
int lastchar;
char n;
uname = popen("sudo python ./return63.py", "r");
lastchar = fread(os, 1, 80, uname);
os[lastchar] = "\0";
n = toString(("%s", os));
printf("THE DIRECT OUTPUT FROM PY IS %s", os);
printf("THE DIRECT OUTPUT For n IS %c", n);
float ia = n - 0;
long p = ia - 0;
float dd = p - 0;
printf("Your OS is %f", dd);
Output from the PY is 'THE DIRECT OUTPUT FROM PY IS 63.0' , which is the correct value,
output from the n is 'THE DIRECT OUTPUT For n IS �'
output from the dd is 'Your OS is Your OS is 236.000000'
The function tostring was pulled from an answered question about how to get the output from another answered question. I have tried with and without this code.
int toString(char a[]) {
int c, sign, offset, n;
if (a[0] == '-') { // Handle negative integers
sign = -1;
}
if (sign == -1) { // Set starting position to convert
offset = 1;
}
else {
offset = 0;
}
n = 0;
for (c = offset; a[c] != '\0'; c++) {
n = n * 10 + a[c] - '0';
}
if (sign == -1) {
n = -n;
}
return n;
}
toString returns an int, so store an int and output an int.
int n = toString(os); // Also removed the obfuscating '("%s", ..)'
printf("THE DIRECT OUTPUT For n IS %d", n);
Also your toString function has undefined behavior because sign might be read without being initialized.
if (a[0] == '-') { // Handle negative integers
sign = -1;
offset = 1;
}
else {
sign = 1;
offset = 0;
}
You have a potential os buffer overflow and you are not doing the null termination of os correctly:
lastchar = fread(os, 1, sizeof(os) - 1, uname); // Only read one byte less
os[lastchar] = '\0'; // changed from string "\0" to char '\0'
And finally you are not checking the input string for digits, you are accepting every input (also the '.' in "63.0"). You might want to stop at the first non-digit character:
for (c = offset; !isdigit((unsigned char)a[c]); c++) {

How to make cross sign based on user-input in C

Hi i'm currently practicing using c in my school, i have a problem to make cross-sign in C based on user-input, my code only work properly when the height is 11
first i made non-user-input code when height=11 (well this is my actual assgnment) and then make some changes here and there
thanks for your answer
#include <stdio.h>
int main(void)
{
int n, i = 1, j = 9, l = 0, height;
char ch = '#';
printf("Enter the height of cross sign : ");
scanf("%d",&height);
n = (height / 2.0) - 0.5;
while (i <= n)
{
printf("%*c%*c\n", i, ch, (2*n - 2*i + 1), ch);
i++;
}
while (n < j)
{
printf("%*c%*c\n", (j - n), ch, (j - n - 1 + l), ch);
n++;
l += 3;
}
return 0;
}
Firstly your code has some compiler error. You missed some semicolons. Secondly your code works fine till 11 cause of the CPL. You can read about it in the link given below :https://en.wikipedia.org/wiki/Characters_per_line
You don't need to see where's the middle, if you have two variables doing the opposite, like one decreasing and the other increasing at the same time.
this is my code to that problem resolved:
int height, i , j, l;
char ch = '#', sp = ' ';
printf("Enter the height of cross sign : ");
scanf("%d",&height);
j=height;
for(i=1;i<=height;i++)
{
for(l=1;l<=height;l++)
{
if(l==i||l==j)
{
printf("%c", ch); //if it's suppose to print '#'
}
else
{
printf("%c", sp); //if it's suppose to print space - ' '
}
}
j--;
printf("\n");
}
return 0;

c: a.exe has stopped working

I am learning how to program in c:
I want to create a program that separates a number into digits, from there I want to store them into an array (which I've already done in the code below). From there I need to print out the number by using the digits to help with producing the same number. The program crashed upon running and I don't know why.
#include <stdio.h>
int power(int a, int b);
int main()
{
//Issue: printing out incorrect numbers
//Fix: Recall that c is treated as a character here when getchar is invoked
#define MAX_SIZE 100
const int TEN = 10;
const int ONE = 1;
int c;
int digitPos, digitHolder, numberPower = 0;
int my_strg[MAX_SIZE];
printf("\n");
while (((c = getchar()) != EOF) && (c != '\n'))
{
my_strg[digitPos] = c - '0';
digitPos = digitPos + ONE;
}
while (digitPos >= 0)
{
int toPower = digitPos - 1;
printf("%10d", power(TEN, toPower));
digitPos = digitPos - 1;
}
return 0;
}
int power(int a, int b)
{
if (b == 0)
{
return 1;
}
else
{
return a * power(a, b - 1);
}
}
Currently the output is the powers required to return the inputted number, but after the print, the program crashes. Could someone please guide me in the right direction as to how I can fix this problem?
Change the while condition while (digitPos >= 0) into while (digitPos > 0)
Because when digipos==0 --> toPower==-1 --> power(TEN, toPower) CRASH
Beside that tiny problem your code is fine

print a integer in c using putchar only

This is an old practice and I am trying to identify where i went wrong with my code: write a c program to print an integer using putchar only. I know one right way to do it is:
void printnumber(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n == 0)
putchar('0');
if (n/10)
printnumber(n/10);
putchar(n%10 + '0');
}
I just want to know why my way of doing it does not work, though as I was trying to debug using step over, it looks there is no problem with my procedure, however, the code is printing some funny character. I thought it is because putchar() read the number as ascii value and print the character corresponding to ascii value, and maybe this is why in the code above, we are using putchar(n%10+'0'), so I tried to add '0' to all my putchar code, but it does not work properly. So here is my code and result without and with '0' when i=-123
void printnumber(int i)
{
if(i/10!=0)
{
putchar(i%10);
printnumber((i-i%10)/10);
}
else if((i/10==0) && (i%10!=0) && (i>0))
putchar(i%10);
else if((i/10==0) && (i%10!=0) && (i<=0))
putchar(-i%10);
}
The first version works like a charm for me.
Here's the function with main.
#include <stdio.h>
#include <stdlib.h>
void printnumber(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n == 0)
putchar('0');
if (n/10)
printnumber(n/10);
putchar(n%10 + '0');
}
int main(int argc, char** argv)
{
int n = atoi(argv[1]);
printnumber(n);
printf("\n");
}
Here's some output:
~/Stack-Overflow/cpp>>./test-44
Segmentation fault
~/Stack-Overflow/cpp>>./test-44 10
10
~/Stack-Overflow/cpp>>./test-44 3456789
3456789
~/Stack-Overflow/cpp>>./test-44 -10
-10
~/Stack-Overflow/cpp>>./test-44 -95823
-95823
~/Stack-Overflow/cpp>>
PS. I am testing on Linux, using gcc 4.7.3.
Now about the second approach...
Adding '0' to the integer value in the call to putchar is absolutely needed.
In the first if block and the last else if block, you have take care of -ve numbers.
Printing 0 is still an issue.
In the first if block, recursion has to be before the print. Otherwise, you will end up printing the digits in the reverse order.
Here's what I came up with:
void printnumber(int i)
{
if(i/10!=0)
{
printnumber(i/10);
if ( i > 0 )
{
putchar(i%10 + '0');
}
else
{
putchar(-i%10 + '0');
}
}
else if((i/10==0) && (i%10!=0) && (i>0))
{
putchar(i%10 + '0');
}
else if((i/10==0) && (i%10!=0) && (i<=0))
{
putchar('-');
putchar(-i%10+'0');
}
}
PS. My version continues to have a problem with the number 0. It doesn't print anything.
if(i/10!=0)
{
putchar(i%10);
printnumber((i-i%10)/10);
}
If i < 0, then the first putchar() is in trouble no matter you + '0' or not.

Optimizing I/O(Output) in C code + a loop

I have a code which reads around (10^5) int(s) from stdin and then after performing ## i output them on stdout. I have taken care of the INPUT part by using "setvbuf" & reading lines using "fgets_unlocked()" and then parsing them to get the required int(s).
I have 2 issues which i am not able to come over with:
1.) As i am printing int(s) 5 million on stdout its taking lot of time : IS THERE ANY WAY TO REDUCE THIS( i tried using fwrite() but the o/p prints unprintable characters due to the reason using fread to read into int buffer)
2.) After parsing the input for the int(s) say 'x' i actually find the no of divisors by doing %(mod) for the no in a loop.(See in the code below): Maybe this is also a reason for my code being times out:
Any suggestions on this to improved.
Many thanks
This is actually a problem from http://www.codechef.com/problems/PD13
# include <stdio.h>
# define SIZE 32*1024
char buf[SIZE];
main(void)
{
int i=0,chk =0;
unsigned int j =0 ,div =0;
int a =0,num =0;
char ch;
setvbuf(stdin,(char*)NULL,_IOFBF,0);
scanf("%d",&chk);
while(getchar_unlocked() != '\n');
while((a = fread_unlocked(buf,1,SIZE,stdin)) >0)
{
for(i=0;i<a;i++)
{
if(buf[i] != '\n')
{
num = (buf[i] - '0')+(10*num);
}
else
if(buf[i] == '\n')
{
div = 1;
for(j=2;j<=(num/2);j++)
{
if((num%j) == 0) // Prob 2
{
div +=j;
}
}
num = 0;
printf("%d\n",div); // problem 1
}
}
}
return 0;
}
You can print far faster than printf.
Look into itoa(), or write your own simple function that converts integers to ascii very quickly.
Here's a quick-n-dirty version of itoa that should work fast for your purposes:
char* custom_itoa(int i)
{
static char output[24]; // 64-bit MAX_INT is 20 digits
char* p = &output[23];
for(*p--=0;i/=10;*p--=i%10+0x30);
return ++p;
}
note that this function has some serious built in limits, including:
it doesn't handle negative numbers
it doesn't currently handle numbers greater than 23-characters in decimal form.
it is inherently thread-dangerous. Do not attempt in a multi-threaded environment.
the return value will be corrupted as soon as the function is called again.
I wrote this purely for speed, not for safety or convenience.
Version 2 based on suggestion by #UmNyobe and #wildplasser(see above comments)
The code execution took 0.12 seconds and 3.2 MB of memory on the online judge.
I myself checked with 2*10^5 int(input) in the range from 1 to 5*10^5 and the execution took:
real 0m0.443s
user 0m0.408s
sys 0m0.024s
**Please see if some more optimization can be done.
enter code here
/** Solution for the sum of the proper divisor problem from codechef **/
/** # author dZONE **/
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
# include <error.h>
# define SIZE 200000
inline int readnum(void);
void count(int num);
int pft[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709};
unsigned long long int sum[SIZE];
int k = 0;
inline int readnum(void)
{
int num = 0;
char ch;
while((ch = getchar_unlocked()) != '\n')
{
if(ch >=48 && ch <=57)
{
num = ch -'0' + 10*num;
}
}
if(num ==0)
{
return -1;
}
return num;
}
void count(int num)
{
unsigned int i = 0;
unsigned long long tmp =0,pfac =1;
int flag = 0;
tmp = num;
sum[k] = 1;
for(i=0;i<127;i++)
{
if((tmp % pft[i]) == 0)
{
flag =1; // For Prime numbers not in pft table
pfac =1;
while(tmp % pft[i] == 0)
{
tmp =tmp /pft[i];
pfac *= pft[i];
}
pfac *= pft[i];
sum[k] *= (pfac-1)/(pft[i]-1);
}
}
if(flag ==0)
{
sum[k] = 1;
++k;
return;
}
if(tmp != 1) // For numbers with some prime factors in the pft table+some prime > 705
{
sum[k] *=((tmp*tmp) -1)/(tmp -1);
}
sum[k] -=num;
++k;
return;
}
int main(void)
{
int i=0,terms =0,num = 0;
setvbuf(stdin,(char*)NULL,_IOFBF,0);
scanf("%d",&terms);
while(getchar_unlocked() != '\n');
while(terms--)
{
num = readnum();
if(num ==1)
{
continue;
}
if(num == -1)
{
perror("\n ERROR\n");
return 0;
}
count(num);
}
i =0;
while(i<k)
{
printf("%lld\n",sum[i]);
++i;
}
return 0;
}
//Prob 2 Is your biggesr issue right now.... You just want to find the number of divisors?
My first suggestion will be to cache your result to some degree... but this requires potentially twice the amount of storage you have at the beginning :/.
What you can do is generate a list of prime numbers before hand (using the sieve algorithm). It will be ideal to know the biggest number N in your list and generate all primes till his square root. Now for each number in your list, you want to find his representation as product of factors, ie
n = a1^p1 * a1^p2 *... *an^pn
Then the sum of divisors will be.
((a1^(p1+1) - 1)/(a1 - 1))*((a2^(p2+1) - 1)/(a2-1))*...*((an^(pn+1) - 1)/(an-1))
To understand you have (for n = 8) 1+ 2 + 4 + 8 = 15 = (16 - 1)/(2 - 1)
It will drastically improve the speed but integer factorization (what you are really doing) is really costly...
Edit:
In your link the maximum is 5000000 so you have at most 700 primes
Simple decomposition algorithm
void primedecomp(int number, const int* primetable, int* primecount,
int pos,int tablelen){
while(pos < tablelen && number % primetable[pos] !=0 )
pos++;
if(pos == tablelen)
return
while(number % primetable[pos] ==0 ){
number = number / primetable[pos];
primecount[pos]++;
}
//number has been modified
//too lazy to write a loop, so recursive call
primedecomp(number,primetable,primecount, pos+1,tablelen);
}
EDIT : rather than counting, compute a^(n+1) using primepow = a; primepow = a*primepow;
It will be much cleaner in C++ or java where you have hashmap. At the end
primecount contains the pi values I was talking about above.
Even if it looks scary, you will create the primetable only once. Now this algorithm
run in worst case in O(tablelen) which is O(square root(Nmax)). your initial
loop ran in O(Nmax).

Resources