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
Related
How do I create a program where the input of a letter (a-z) is converted to ASCII and printed out. I am stuck at the point where it has to show all the ASCII numbers before it.
Let's say if the user inputs the character c, I want to print out 97,98,99 for character inputs a,b,c respectively.
I am somewhat a beginner. Pretty sure I have to use a loop.
Hi, as I am a beginner can you possibly check my way of doing it, unsure where I am doing wrong. Your code has a few things which I am unfamiliar with. I am aiming to restrict it to only A-Z. So here's the code :
#include <stdio.h>
int main()
{
char c,z;
printf("Enter An English upper case letter: ");
scanf("%c", &z);
for (c=65;c<91;c++)
{
if(c==z)
printf("%c",z);
}
return 0;
}
#include <stdio.h>
void get_ASCII_value(char c)
{
printf("The ASCII value of %c = %d", c, c);
}
int main(void)
{
char c;
printf("Enter a character: ");
scanf("%c", &c);
get_ASCII_value(c);
return 0;
}
To clarify, %d prints the ASCII value for that specific char
As for your specific case:
#include <stdio.h>
int main()
{
char c,z;
printf("Enter An English upper case letter: ");
scanf("%c", &z);
if (z < 65 || z > 90)
return 0;
for (c = 65; c <= z; c++)
printf("The ASCII value of %c = %d\n", c, c);
return 0;
}
#include <stdio.h>
#include <stdint.h>
#include <limits.h>
int main(void)
{
for(uint8_t c = 0; c < UCHAR_MAX; ++c)
{
uint8_t out[2] = {c};
printf("%d (%s)\n", c, isprint(c)? out : "*unprintable*");
}
return 0;
}
###Output
Success #stdin #stdout 0s 4288KB
0 (*unprintable*)
1 (*unprintable*)
2 (*unprintable*)
3 (*unprintable*)
4 (*unprintable*)
5 (*unprintable*)
[....]
29 (*unprintable*)
30 (*unprintable*)
31 (*unprintable*)
32 ( )
33 (!)
34 (")
35 (#)
36 ($)
37 (%)
38 (&)
39 (')
40 (()
41 ())
42 (*)
43 (+)
[...]
65 (A)
66 (B)
67 (C)
68 (D)
69 (E)
70 (F)
71 (G)
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;
}
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 learning C and practicing by writing a small program that reads integers from a textfile and stores them into an array. However, the integers never get stored somehow and the array is empty.
int readNumbers(int array[], char* fname) {
78
79
80 int numberRead = 0;
81 FILE* fp;
82 int ch;
83 int i = 0;
84
85
86
87 fp = fopen(fname, "r");
88 // Test to see if the file was opened correctly
89
90 if (fp == NULL) {
91 printf("Error opening file\n");
92 return;
93 }
94 // Now read until end of file
95
96 while (ch = fgetc(fp) != EOF && isdigit(ch)) {
97 array[i++] = ch;
98 }
99 if (ferror(fp)) {
100 return;
101 }
102 // Close the file pointer
103
104 fclose(fp);
105
106 // Return the number of items read
107 return numberRead;
108 }
The text file would be something like this:
1 2 3 4 5 6 7 8 9
Thanks in advance.
I've updated the code. This almost works, but it interprets characters such as 55 as 5 and 5. So my array would have two 5's.
while ((ch =fgetc(fp)) != EOF) {
97 if (ch != ' ' && ch != '\n') {
98 array[counter] = ch - '0';
99 counter++;
100 numberRead++;
101 }
102 }
To expand on what Matt McNabb said in the comment, you can't have return without a value (unless it's inside a void function). Your readNumbers() function is declared to return int so all return paths must return an int. You may like to return -1 if there's a file error, since 0 is (kind of :) ) a valid number of chars to read.
Since there are spaces between the digits in your input file you will need to change the logic in your while loop.
while ((ch = fgetc(fp)) != EOF && isdigit(ch))
will fail as soon as it reads a non-digit char.
I should also mention that you are storing the numerical value of each char you read into your array, which might not be what you want. Eg, in ASCII a '0' char will have a numeric value of 48, '1' has a value of 49, etc.
PS. Make sure that the function that calls readNumbers() provides an array big enough to handle any possible result...
Try to avoid using exit() deep within your program, when practical, and just use it in main(). Also, rather than just killing your program stone dead with exit() it's much better to print some kind of error message first (usually to stderr), and then die gracefully. As for creating suitable error messages, check out the <stdio.h> function perror(), and take a look at <errno.h>.
You can either print the error message in readNumbers() and return -1, and then let the calling function (eg main()) decide if the error's so bad that the program should die. Or let the calling function handle the printing of the error message, too.
you should us the parentheses here while (ch = fgetc(fp) != EOF && isdigit(ch)) , it should be while ((ch = fgetc(fp)) != EOF && isdigit(ch)) otherwise you will store in ch the value of fgetc(fp) != EOF which is eather 1 or 0 ( TRUE or FALSE)
// this following code modification will handle your most recent question
int value = 0; // place to accumulate numbers
int inNumber = 0; // to avoid spurious input in array[]
// note: the following expects that 'ch' is defined as an integer
while ((ch =fgetc(fp)) != EOF)
{
if (ch >= '0' && ch <= '9') // only process numeric characters
{
value *= 10;
value += (ch - 0x30); // convert alpha to binary
inNumber = 1;
}
else
{ // break between numbers
if( 1 == inNumber )
{
array[counter] = value;
counter++;
numberRead++;
value = 0; // reset for next number
inNumber = 0;
}
}
}
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).