I'm following along with a book on C to learn it and I am writing all the code in the book to follow along, the latest one to do with arrays is supposed to say how many white spaces, tabs etc. There are but when I execute it, nothing shows up, it's just blank, as in I can type something then press enter and nothing happens, is it supposed to tell me how many of each thing there is?
I am too new to understand if this program is actually supposed to output anything so I thought I would post it on here and get an opinion, it compiles and runs fine, no errors, but the book sort of refers to it outputting stuff, but nothing happens when I'm running it and typing stuff in, can just keep typing stuff forever.
Here is the code
#include <stdio.h>
int main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[1]);
printf(", white space = %d, other = %d\n", nwhite, nother);
}
The application takes in input some values and then counts the number of digits (0-9) and the white spaces. The key combination to interrupt the cycle is not ENTER but EOF which in Linux is CRTL-D and in WINDOWS is CTRL-Z.
Then, in you application there is a bug :
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[1]);
In order to show the number of digits this should be :
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
Unfortunately, getting interactive input is quite problematic when using scanf(), getchar(), fgets(), etc. That's why most people usually write their own custom functions, often getting a whole line from stdin and then parsing it according to their needs. However, if you want to use ENTER to stop the cycle you can modify the code as follows, but you will lose the possibility to count the number of new lines in the input.
#include <stdio.h>
int main(void)
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != '\n')
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
return 0;
}
This should work as you expected. However, you should consider to write a better input function, there are several interesting solution online.
EDIT
The main() must return int. Not void, not bool, not float. int. Just int, nothing but int, only int. Some compilers accept void main(), but that is non-standard and shouldn't be used.
Check some examples here : http://www.parashift.com/c++-faq-lite/main-returns-int.html
You can provide a EOF using following
WINDOWS:
Press F6 then ENTER
or
Ctrl+Z
LINUX:
Ctrl+D
Change
printf(" %d", ndigit[1]);
to
printf(" %d", ndigit[i]);
Press ctrl+d to give EOF after entering value
Input:
2 4 6 8 //3 white space + 1 new line = 4 white space
[ctrl + d]
Output:
digits = 0 0 1 0 1 0 1 0 1 0, white space = 4, other =0
Related
I am reading the C programming language book Dennis M. Ritchie and
trying to solve this question:
Write a program to print a histogram of
the lengths of words in
its input. It is easy to draw the histogram with the bars horizontal; a vertical
orientation is more challenging.
I think my solution works, but the problem is that if I don't press EOF, the terminal won't show the
result. I know that the condition specifies that exactly, but I am
wondering whether there is any way to make the program terminate after
reading a single line? (Sorry if my explanation of the problem is a bit shallow. Feel free to ask more.)
#include <stdio.h>
int main ()
{
int digits[10];
int nc=0;
int c, i, j;
for (i = 0; i <= 10; i++)
digits[i] = 0;
//take input;
while ((c = getchar ()) != EOF) {
++nc;
if (c == ' ' || c=='\n') {
++digits[nc-1];
//is it also counting the space in nc? i think it is,so we should do nc-1
nc = 0;
}
}
for (i = 1; i <= 5; i++) {
printf("%d :", i);
for (j = 1; j <= digits[i]; j++) {
printf ("*");
}
printf ("\n");
}
// I think this is a problem with getchar()
//the program doesn't exit automatically
//need to find a way to do it
}
You could try to make something like
while ((c = getchar ()) != EOF && c != '\n') {
and then adding a line after the while loop to account for the last word:
if (c == '\n') {
++digits[nc-1];
nc = 0;
There is also another problem inside your program. ++digits[nc-1]; is correct, however, for the wrong reason. You should make it because an array starts at zero, i.e. if you have an array of length 10, it will go from 0 to 9, so you should count the length of the words and then add one to the position of the array length - 1 (as there are no words of length zero). The problem is that you are still counting the blank spaces or the newline characters inside the length of a word, so if you have two blank spaces after a word of length 4, the program will add to the array a word of length 5 + a word of length 1. To avoid this, you should do something like this:
while ((c = getchar ()) != EOF) {
if ((c == ' ' || c == '\n' || c == '\t') && nc > 0) {
++digits[nc-1]; // arrays start at zero
nc = 0;
}
else {
++nc;
}
}
I'm currently learning C from The C Programming Language by Brian W Kernighan and Dennis M. Ritchie. I've gotten to the arrays section, and ran into a problem. When arrays are discussed in this book, they use this program:
`#include <stdio.h>
/* This program count digits, white space, others */
main()
{
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF){
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c == ' ' || c == '\n' || c == '\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; ++i)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n",
nwhite, nother);}
}`
My question is: why the -'0' in ++ndigit[c-'0'];? What does it mean? I noticed when I get rid of it, the program will not function properly. Edit: I heard it has something to do with ASCII. I have no idea what that is.
If c is between '0' and '9', due to c standard '0' to '9' are encoded consecutively, c-'0' will give out the numerical result of c. Say c is '6', then c-'0'==6.
I'm trying K&R exercise 1-29 and honestly I'm stumped by what my program is doing. Upon inputting a small text file with gcc, the program just runs forever as if there's an infinite loop. Reading through my loops again I can't see any obvious mistakes, so I tried to print different variables to see what's happening, but nothing's printing to the command line - even the variable i from the very first for loop, not even once. Here's my code:
#include <stdio.h>
#define tabStop 10
#define maxInput 1000
int main(){
int i, c, b;
int m, t = 0;
int index, index2;
char input[maxInput];
int nonBlank;
for (i = 0; i<maxInput-1 && (c=getchar()) != EOF; ++i){
if (c != ' '){
input[i] = c;
}
else {
index = i; /*stores location in character array at start of blanks*/
for (b = 0; c == ' '; ++b, ++i); /*counts the number of blanks (b) until the next non-blank character*/
nonBlank = input[i]; /*saves the first seen non-blank character to be re-added later (as getchar() will have taken it in from input and will now stay at that point of the input)*/
index2 = i; /*stores location in character array at end of blanks*/
if (b >= tabStop){ /*if the tab space fits inside the number of blanks, otherwise there is nothing to be done*/
while (t < b){
t += tabStop;
++m;
}
for (int x = 0, i = index; i != index2 && x <= m; ++i, ++x){ /*loops over the number of tabs to be added starting from the first blank in the array found up until the first non-blank*/
input[i] = '\t';
}
while (i != index2){ /*if i did not reach index2 before x surpassed m, there exist remaining spaces to be filled with blanks*/
input[i] = ' ';
++i;
}
}
input[i] = nonBlank; /*puts the first seen non-blank character into place, as getchar() has already covered it and so it wouldn't otherwise be added like other non-blanks*/
}
}
input[i] = '\0';
printf("%s", input);
return 0;
}
Here's the inputted text file:
hello there world
I am creating a program where I insert a number of sentences and the program outputs them in order. I have finished the program, but when I run it it seems like the characters I input into the array aren't displayed or stored correctly, getting as a result random letters instead of the full sentence. Here is the code of the program:
char ch;
int i,j,k;
int nothing = 0;
int count = 1;
char lines[5][256];
int length[256];
int main() {
printf("Please insert up to a max of 5 lines of text (Press enter to go to next line and twice enter to stop the program):\n");
i = 0;
while (i<5){
j = 0;
ch = getche();
if (ch == '\r'){
if(i!= 0){
break;
}
printf("You have not inserted anything, please insert a line:");
i=-1;
}
if(ch != '\r'){
lines[i][j]=ch;
while (ch!='\r'){
ch = getche();
lines[i][j] = ch;
j++;
}
}
printf("\n");
i++;
}
for (k=i ; k > 0; k--){
printf("\tphrase %i :", count);
for ( j =0 ; j <= length[k]; j++){
printf("%c",lines[j][k]);
}
count++;
printf("\n");
}
return 0;
}
How can I get the characters to be stored and displayed correctly? Any help is appreciated, thank you!!
There are numerous problems with your code. I'll try and summarise here, and give you improved code.
Fist, some changes that I made to get this to compile on my system:
Changed getche() to getchar() (getche() does not appear to be available on Ubuntu).
I took out the section about re-entering a string, and just focused on the rest (since the logic there was slightly broken, and not relevant to your question). It will still check for at least one line though, before it will continue.
I had to change the check for \r to \n.
I changed your length array to size 5, since you'll only have the lengths of maximum 5 strings (not 256).
Some problems in your code:
You never updated the length[] array in the main while loop, so the program never knew how many characters to print.
Arrays are zero indexed, so your final printing loops would have skipped characters. I changed the for parameters to start at zero, and work up to k < i, since you update i after your last character in the previous loop. The same with j.
Your reference to the array in the printing loop was the wrong way around (so you would've printed from random areas in memory). Changed lines[j][k] to lines[k][j].
No need for a separate count variable - just use k. Removed count.
The nothing variable does not get used - removed it.
#include <stdlib.h>
#include <stdio.h>
char ch;
int i,j,k;
char lines[5][256];
int length[5];
int main()
{
printf("Please insert up to a max of 5 lines of text (Press enter to go to the next line and twice enter to stop the program):\n");
i = 0;
while (i<5)
{
j = 0;
ch = getchar();
if ((ch == '\n') && (j == 0) && (i > 0))
{
break;
}
if (ch != '\n')
{
while (ch != '\n')
{
lines[i][j] = ch;
j++;
ch = getchar();
}
}
length[i] = j;
printf("\n");
i++;
}
for (k = 0; k < i; k++)
{
printf("\tPhrase %i : ", k);
for (j = 0; j < length[k]; j++)
{
printf("%c", lines[k][j]);
}
printf("\n");
}
return 0;
}
Behavior is very inconsistent-- very frustrating.
The problem must lie in pasting some input text into Xcode's Debug Area.
Here's how to replicate the problem:
#include <stdio.h>
/* count digits, white space, others */
main() {
int c, i, nwhite, nother;
int ndigit[10];
nwhite = nother = 0;
for (i = 0; i < 10; ++i)
ndigit[i] = 0;
while ((c = getchar()) != EOF)
if (c >= '0' && c <= '9')
++ndigit[c-'0'];
else if (c==' '||c=='\n'||c=='\t')
++nwhite;
else
++nother;
printf("digits =");
for (i = 0; i < 10; i++)
printf(" %d", ndigit[i]);
printf(", white space = %d, other = %d\n", nwhite, nother);
}
Run this C code in Xcode
Paste in some Lorem Ipsum into Xcode Debugger Area
⌃d will not send EOF signal
Doesn't work even if you send Ctrl-d on its own line.
Note** Works fine (pasting in lipsum and signaling EOF with ⌃d) when you run the compiled executable from Terminal. Also, Ctrl-d doesn't need to be on its own line (just keystroked twice in a row). Still works regardless.