I have wrote a program that takes two integers(m and n) as input and then writes to a file all the prime numbers between them. I wanted the output to look neat so I print each number 7 spaces wide using the field-width modifier and only print 10 per line. The output is as expected apart from the first line, where only 9 numbers are printed.
Here is the code:
#include <stdio.h>
#include <math.h>
#define SIZE 100000000
char primes[SIZE];
void seive(void)
{
int i, j;
primes[1] = primes[0] = 1;
for (i=3;i<=sqrt(SIZE);i+=2)
if (primes[i] == 1)
continue;
else
for (j=i*i;j<SIZE;j+=2*i)
primes[j] = 1;
}
int main()
{
int n, m, count;
FILE *fp;
fp = fopen("test.txt", "w");
seive();
scanf("%d %d", &m, &n);
count = 0;
if (m <= 2) {
fprintf(fp, "%7d ", 2);
count++;
}
if (!(m & 1))
m++;
for (m;m<=n;m+=2) {
if (!primes[m]) {
count++;
if (count == 10) {
fprintf(fp, "\n");
count = 0;
}
fprintf(fp, "%7d ", m);
}
}
return 0;
}
This is the output for the input 1 300:
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
As you can see only nine numbers are printed on the first line, but after it does as it should. I'm baffled. Thanks in advance.
I think it has something to do with the fact that you print your newline before you print your output in the loop.
change it to:
for (m;m<=n;m+=2) {
if (!primes[m]) {
count++;
fprintf(fp, "%7d ", m);
if (count == 10/*&& you're going to print more numbers*/) {
fprintf(fp, "\n");
count = 0;
}
}
}
count = 0;
if (m <= 2) {
fprintf(fp, "%7d ", 2);
count++;
}
This starts a line, prints an entry, and increments count to 1.
if (!primes[m]) {
count++;
if (count == 10) {
fprintf(fp, "\n");
count = 0;
}
fprintf(fp, "%7d ", m);
This starts a line, prints an entry, and sets count to zero.
Since the two code sections set count to different values (off by one), the produce different numbers of entries per line (off by one).
Related
I am writing a program to compress a file consisting of hexadecimal values into run-length code. For example, given a file:
46 6f 6f 20 62 61 72 21 21 21 20 20 20 20 20
my code should produce the following file:
01 46 02 6f 01 20 01 62 01 61 01 72 03 21 05 20
I don't know why the program I've written gets stuck. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
int main(void){
int a, b, c, count=1, flag=TRUE;
FILE *file;
FILE *out;
file = fopen("input.txt", "r");
if(file){
out = fopen("input.txt.out", "a");
fscanf(file, "%x", &a);
while(fscanf(file, "%x", &c)){
while(flag==TRUE){
if(c==a){
count= count+1;
}else{
flag = FALSE;
}
b=a;
a=c;
}
fprintf(out, "%d %02x ", count, b);
count = 1;
flag = TRUE;
}
}else{
printf("ERROR: file not found.");
}
}
EDIT: I updated the code removing the !feof(file) argument and replacing it with an actual I/O function instead. Thanks for the insight. However, my program still doesn't work.
I don't know why your program "gets stuck" but this might work better. Note I have dumped the meaningless a, b, c and the truth stuff.
#include <stdio.h>
#include <stdlib.h>
int main(void){
int lastchar, thischar, count;
FILE *finp;
FILE *fout;
finp = fopen("input.txt", "r");
fout = fopen("output.txt", "w"); // changed "a" to "w"
if(fout == NULL || finp == NULL) {
puts("Error opening file(s)");
exit(1);
}
count = 1;
fscanf(finp, "%x", &lastchar);
while(fscanf(finp, "%x", &thischar) == 1) { // func value better then feof
if(thischar == lastchar) {
count++;
}
else {
fprintf(fout, "%02X %02X ", count, lastchar);
count = 1;
}
lastchar = thischar;
}
fprintf(fout, "%02X %02X ", count, lastchar); // discharge remaining
fclose(fout);
fclose(finp);
return 0;
}
Program input: 46 6f 6f 20 62 61 72 21 21 21 20 20 20 20 20
Program output: 01 46 02 6F 01 20 01 62 01 61 01 72 03 21 05 20
A better way of implementing RLE is to choose an "escape" value to define when a compression follows. Thus 3 values will encode a compression sequence, and so it is only worth compressing 3 or more the same. All other characters are verbatim, except the escape character itself.
I have an assignment where I'm suppose to read input lines such as
2
67 5 100 1 11 97 98 10 1 110
15 72 10 101 47 67 88 20 94 6 22 11
4
61 11 93 4 73 39 78 34 17 104
23 43 11 93 65 52 20 96 66 31 86 24 40 61 102 13 50 51
73 43 28 73 8 89 31 68 77 27 24 77 42 72 15 24 64 51
25 75 7 90 10 111 17 16
.....
process every two integers (the first line in a block only tells us how many words we will process), add them then match
them to their corresponding ASCII char. The example above would be two blocks.
The output should be:
Decoded messages:
Hello World!
Happy Bhutanese teacher's day!
I'm having problems when it comes to dealing with a file with multiple blocks, more than 20 and so forth following the same format on one input text. I can handle one block fine, two blocks okay but not fine because my program doesn't seem to end. No line will be longer than 256 characters. numOfPuzzl refers to how many words we process per block.
I'd greatly appreciate any help. I attached my code and commented as much as I can too.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
//user will type in file name they choose to process and we allocated in filename[]
char filename[256];
printf("Enter filename: ");
scanf("%s", filename);
//process filename username typed in
FILE *pFile;
pFile = fopen(filename, "r");
//if there's nothong to read
if (pFile == NULL){
exit(1);
}
printf("Decoded messages:\n");
//create array we will putting lines into
char myString[256];
//simply gets the first line, which is always a lone integer
fgets(myString, 256, pFile);
int numOfPuzzl;
sscanf(myString, "%d", &numOfPuzzl);
//printf("puzzles to solve: %d\n", numOfPuzzl);
int wordsProcessed = 0;
//just remember that myString has entire line
//start processing the lines that follow, a line is a word
while (fgets(myString, 256, pFile) != NULL){
int num = 0; //first integer in line
int secondNum = 0; //second int. in line
int tot = 0; //how many bytes
int bytes_read = 0; //bytes processed
char *endOfStrAdr = strchr(myString, '\0'); //returns address of end terminating char.
int endOfStrIdx = endOfStrAdr - myString; //this will give me the index of where the terminating char. occurs within my array
//start scanning integers within array making sure to not sccan out of bounds
while (tot < endOfStrIdx){
//first integer allocated as well as how many byes it was
sscanf(myString + tot, "%d %n", &num, &bytes_read);
tot += bytes_read; //keeps tab so we don't have to read from the begn. of array everytime
//second integer allocated as well as how many byes it was
sscanf(myString + tot, "%d %n", &secondNum, &bytes_read);
tot += bytes_read; ////keeps tab so we don't have to read from the begn. of array everytime
printf("%c", (char) num + secondNum); //add the two integers and cast them to char
//we want to check if we are the end of the string, our word
if (tot == endOfStrIdx){
printf(" ");
wordsProcessed++;
//we want to print a new line char. if we finished processing all the words for the puzzle
if (wordsProcessed == numOfPuzzl){
printf("\n");
fgets(myString, 256, pFile);
}
}
}
}
fclose(pFile);
}
Ignore blank lines between puzzles.
Reset parameters (numOfPuzzl and wordsProcessed) before processing new puzzles.
To archive that, change
if (wordsProcessed == numOfPuzzl) {
printf("\n");
fgets(myString, 256, pFile);
}
into
if (wordsProcessed == numOfPuzzl) {
printf("\n");
while ( fgets(myString, 256, pFile) != NULL ){
if ( sscanf(myString, "%d", &numOfPuzzl) == 1 )
break;
}
wordsProcessed = 0;
}
I suggest like this:
#include <stdio.h>
#include <stdlib.h>
//stringize macro
#define S_(x) #x
#define S(x) S_(x)
int main(void){
char filename[FILENAME_MAX + 1];
printf("Enter filename: ");
scanf("%" S(FILENAME_MAX) "[^\n]", filename);
FILE *pFile;
if(NULL==(pFile = fopen(filename, "r"))){
perror("can't opne file");
exit(EXIT_FAILURE);
}
printf("Decoded messages:\n");
int numOfLines;
while(1==fscanf(pFile, "%d", &numOfLines)){
for(int i = 0; i < numOfLines; ++i){
int num1, num2, state;
char ck;
while(3==(state=fscanf(pFile, "%d %d%c", &num1, &num2, &ck)) || 2 == state){
putchar(num1 + num2);
if(state == 2 || state == 3 && ck == '\n')
break;
}
putchar(' ');
}
putchar('\n');
}
fclose(pFile);
return 0;
}
i have wrote a simple code that prints all the prime numbers from the number that has entered. I would like to print how many prime numbers are printed. I think its print("%d",c++); but i dont know where to put it. I have tried putting it right before return 0; at the end of prime method but it does not work. The prime numbers print just fine but the counter does not print.
void main(void){
int pri;
scan("%d",&pri);
prime(pri);
}
void prime(int n){
int m,i,c,x;
for(m = 1;m<=n;m++){
c = 0;
for(i=2;i<=m/2;i++){
if(m%i==0){
c++;
break;
}
}
if(c==0 && m!= 1){
printf("%d ",m);
}
}
print("the count is: ");
print("%d",c);
return 0;
}
If I input 100 I want the output to be:
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
The count is 25.
Add a variable count since c is not your count. It is a local test variable whether a prime has been found. add int count = 0; in front of the for loop and print it instead of c at the end. In the if statement where you print the single primes, add count++;.
int n = 100; // for copy paste purposes
int m,i,c,x;
int count = 0;
for(m = 1;m<=n;m++){
//c = 0;
for(i=2;i<=m/2;i++){
if(m%i==0){
c++;
break;
}
}
if(c==0 && m!= 1){
printf("%d ",m);
count++;
}
}
printf("\nthe count is: %d\n", count);
There are quite a few things your program should take care of most importantly it should compile first which I highly doubt it does at this point.Anyway below is a working example for it, with modifications
#include <stdio.h>
void prime(int ); // prototype
//void main(void){
int main(void){
int pri;
//scan("%d",&pri);
scanf("%d",&pri);
prime(pri);
return 0;
}
void prime(int n)
{
int m,i,c,count = 0; // your counter
for(m = 1 ; m <= n ; m++ ) {
c = 0;
for( i = 2 ; i <= m/2 ; i++ ) {
if( m%i == 0 ) {
c++;
break;
}
}
if( c == 0 && m != 1 ){
printf("%d ",m);
count = count + 1; // keep counting
}
}
//print("the count is: ");
printf("\nthe count is: ");
//print("%d",c);
printf("%d",count);
// return 0;
}
Note - better formatting the key.
My program gives me error(not exactly an error but it just prints error instead of even or odd) even if I put a number or letters. The code works if I remove the isdigit checker(3rd line). I do no know what am I doing wrong. Can someone please help me. Thanks in advance. Here is my code.
int main()
{
int n;
printf("Input an integer\n");
scanf("%d", &n);
if(!isdigit(n))
{
print("error");
return 0;
}
n%2 == 0 ? printf("Even\n") : printf("Odd\n");
return 0;
}
isdigit is not for this purpose.
If you want to check if the input is vaild, one method is to load with %s and use strtol.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void print(const char *s) {
puts(s);
}
int main()
{
char nstr[100] = {0};
int n;
char *e;
printf("Input an integer\n");
scanf("%99s", nstr);
n=(int)strtol(nstr, &e, 10);
if(nstr[0] == '\0' || *e != '\0')
{
print("error");
return 0;
}
n%2 == 0 ? printf("Even\n") : printf("Odd\n");
return 0;
}
man -a isdigit
isdigit()
checks for a digit (0 through 9).
Thus isdigit fails if ascii value of n is not anything but
Oct Dec Hex Char
--------------------------
060 48 30 0
061 49 31 1
062 50 32 2
063 51 33 3
064 52 34 4
065 53 35 5
066 54 36 6
067 55 37 7
070 56 38 8
071 57 39 9
man -a ascii
thus,
if(!isdigit(n))
{
print("error");
return 0;
}
is not an appropriate option. you should probably find some other option to validate n.
The isdigit function checks a character to see if it is in the '0' to '9' range. More specifically, it checks if the ASCII value of the character is between 48 (the code for '0') and 57 (the code for '9').
You're passing an int to this function, not a character, so it's not appropriate to use this function here. Just remove this check and it will work.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n;
printf("Please enter your number\n");
scanf("%d",&n);
if( n%2==0)
printf("The number is even\n");
else
printf("The number is odd\n");
System("pause");
return 0;
}
Check this one.
I am a beginner programmer taking a class and I cannot get my output strings to print with spaces in between words. Here is my code below. It is supposed to take a string that I input and either change to all caps or all lower case as I specify when I run the program. If I put in MY CODE DOES NOT WORK, it outputs mycodedoesnotwork. Why is it removing the spaces?
1 #include <stdio.h>
2 #include <assert.h>
3 #include <stdlib.h>
4 #include <string.h>
5
6
7 int shout(char * msgIn, char * msgOut) {
8
9 if (!msgIn || !msgOut)
10 return -1;
11 while (*msgIn != '\0') {
12 if ('a' <= *msgIn && *msgIn <= 'z')
13 *msgOut = *msgIn + ('A' - 'a');
14 else
15 *msgOut = *msgIn;
16 msgIn++;
17 msgOut++;
18 }
19 *msgOut = '\0';
20
21 return 0;
22 }
23
24
25 int whisper(char const * msgIn, char * msgOut) {
26 if (!msgIn || !msgOut)
27 return -1;
28 while (*msgIn != '\0') {
29 if ('A' <= *msgIn && *msgIn <= 'Z')
30 *msgOut = *msgIn + ('a' - 'A');
31 else
32 *msgOut = *msgIn;
33 msgIn++;
34 msgOut++;
35 }
36 *msgOut = '\0';
37 return 0;
38 }
39
40 int main(int argc, char ** argv) {
41 char in[128], out[128];
42 int i;
43 for (i = 1; i < argc; i++) {
44 if (strcmp("-w", argv[i]) == 0)
45 while (scanf("%s", in) != EOF) {
46 whisper(in, out);
47 printf("%s", out);
48 }
49 else if (strcmp("-s", argv[i]) == 0)
50 while (scanf("%s", in) != EOF) {
51 shout(in, out);
52 printf("%s", out);
53 }
54 }
55 printf("\n");
56 return 0;
57 }
~
~
The scanf calls are reading in just the words (no spaces) and you are not adding spaces back in when you output your strings.
If you don't mind a trailing space, just change lines 47 and 52 to printf("%s ", out)
while (scanf("%s", in) != EOF)==> scanf() takes input up to space and send to function
and then in next iteration again takes word after space.
You need to use fgets() instead.
It is not problem with your shout() or wisper() functions, but problem with scanf().
When you specify %s to read string, the string will terminate at any white space chars - space, tab etc.
And that will not be included in the string. So space that you enter between the strings are not stored in in variable.
You may want to think of different approach to solve that.
The space is a string terminator for scanf() and scanf() does not include it in the acquired string. man 3 scanf