Cannot Print Variable Value that Was Incremented in Loop - c

I am currently trying to learn the C programming language and am using Kernighan and Ritchie's The C Programming Language, Second Edition. I am trying to write a program similar to an example they give in the book in chapter one regarding text streams.
My program is supposed to print out a text file to the terminal and then count the number of characters before printing that figure too. This is my code:
#include <stdio.h>
int main()
{
int count = 0, c;
while ((c = getchar()) != EOF) {
count++;
putchar(c);
}
printf("\n%d characters\n", count);
return 0;
}
This is the output:
This is a simple file
With two very small lines
I mean three
1 characters
But when I add in this line below count++:
printf("%d", count);
The result is:
1T2h3i4s5 6i7s8 9a10 11s12i13m14p15l16e17 18f19i20l21e22
23W24i25t26h27 28t29w30o31 32v33e34r35y36 37s38m39a40l41l42 43l44i45n46e47s48
49I50 51m52e53a54n55 56t57h58r59e60e61
1 characters
This means that count is being incremented, but I cannot access its value from outside of the while loop. I thought that if the declaration of the variable (in this case int count = 0 is outside the loop), then the value could still be reached after the loop.
If it makes a difference, this is what I call it with:
./example <text.txt
Am I making a silly mistake? Any help would be appreciated. Thanks
Update
I do not know if it makes a difference, but the compiler I am using is: powerpc-apple-darwin9-gcc-4.0.1. Is that what the problem is?
Update 2
This is the command I used to compile the source: gcc -Wall example.c -o example. A weird thing has just happened though. It worked perfectly when I ran this:
#include <stdio.h>
int main()
{
int count = 0, c;
while ((c = getchar()) != EOF) {
count++;
putchar(c);
}
printf("x");
printf("\n%d characters\n", count);
return 0;
}
The output was:
This is a simple file
With two very small lines
I mean three
61 characters
The only difference between this code and the code above is the printf("x") line. I don't understand why it suddenly works if I print something else and I don't understand why it isn't visible. Any character can be put in the command and the same result happens. If more than one character is added, then the second one, and any after that, is printed.

Most likely your reference of characters to where characters are stored in memory is incorrectly coded which is why your output comes out like that. Ensure that the file and text within are correctly referenced. Other than that, the code seems OK.
I think this is what you should do:
int count = 0, c;
FILE *file = fopen("example.txt", "r");
while ((c = getc(file)) != EOF) {
count++;
putchar(c);
}
printf("\n%d characters\n", count);
fclose(file);

Try issuing a fflush(stdout) immediately before the
printf("\n%d characters\n", count);
FYI: your origninal code executes as expected on Ubuntu 14.04 Linux.

Related

Getchar() keeps returning 1

i am new to StackOverflow. I hope to be able to learn a lot here.
So, i'm a beginner in C. I'm just trying a few things, like using very basic functions.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{ int c;
int i,wl[20];
int count = 0;
i = 0;
printf("Insert line: ");
while(c= getchar() != '\n'&& c != EOF)
printf("integer value of the variable is %d\n", c);
return 0;
}
This should be an easy program: you insert an input and gives you the current value in int.
The problem is: getchar keeps returning 1, no matter what.
Also, i have another question. I know that char in C is basically an 8 bit integer and as a matter of fact you can using char and int (with some problems, as integer are not 8 bit variables) interchangeably. So: why do some people declare a variable as int instead of char when in need to store a char with getchar? Sorry for such basic questions.
N.B: other variables are declared as this is part of a bigger code. all the other parts of the code were put as code in order to test this (/* */).
Sorry for my English, i hope what i wrote is clear.
This:
c= getchar() != '\n'
is equivalent to
c = (getchar() != '\n')
so not at all what you meant. So the 1 is the result of the != comparison. You need
(c = getchar()) != '\n'

Executing Error - Program stops working (C)

I need to write a simple program that reads numbers from a file, then stores those numbers in an array. The last number in the file is 0 so the program knows when to reading.
When I execute the program, Dec C++ crashes. I went online for solutions and changed the settings accordingly but that didn't work. I ran other programs I have and it works fine, which makes me think there's something wrong with the code.
Any ideas?
#include <stdio.h>
int main(){
int i, j=0, k;
int values[20];
FILE*ptr;
ptr = fopen("input.txt", "r");
fscanf(ptr, "%d", &i);
while (i=!0){
values[j]=i;
j++;
fscanf(ptr, "%d", &i);
}
for (k=0; k<20; k++)
printf("%d\n", values[k]);
fclose (ptr);
return 0;
}
Another typo:
while (i=!0){
should be:
while (i != 0){
Your code was assigning !0 to i, instead of comparing i with 0. !0 is 1, so you had an infinite loop, and you were writing beyond the bounds of the array.
Also note that if the file has more than 20 numbers in it, you'll write outside the array. And if it has fewer than 20 numbers, the loop that prints values[k] will read uninitialized array entries.
There are a couple of things that are wrong with the code:
You are not checking for error after opening input.txt
While i=!0 is syntactically correct it probably does not do what you want !0 is 1, so it is the same as i=1, you are putting value 1 into i
To help you with debugging:
add printf() statements to your code to verify that you reached a certain line and to check the values of the variables
learn to use a debugger

How am i using getchar() wrong?

OK so basically I'm trying to get a program that transforms a hexadecimal that i enter into its equivalent base 10 value, i'm pretty sure the algorithm is correct, i just cant get it to correctly read what i enter, any help is much appreciated :) And I'm sorry to anyone who thinks this is a really stupid question.
int main()
{
char hexalpha[] = "aAbBcCdDeEfF";
int i, c;
int answer = 0;
c = getchar();
for (i= 0; answer == 0 && hexalpha[i] != "\0"; ++i)
{
if(hexalpha[i]== c)
answer = (10 + (i/2));
}
return answer;
}
You can't compare strings with != , and hexalpha[i] is a char. So you'd want hexalpha[i] != '\0' instead of hexalpha[i] != "\0"
Returning the answer from main() is a bit clumsy, printing out the answer would be easier, so do
printf("Answer: %d\n", answer);
return 0;
You are returning answer, not printing it. Your problem isn't input, it's output. Return passes the value to whatever function called it (or gives an exit status in the case of main).
At the beginning of your code, add the following:
#include <stdio.h>
At the end of main, replace return answer; with:
printf("%i\n", answer);
return 0;
Also, I'd recommend replacing "0" with '0' in the for loop. Your compiler will give you a warning because it should be a char, not a *char.
There doesn't seem anything wrong with your use of getchar. There is however a problem with the second half of your loop-condition: you compare an int (c) with a string ("\0"). You probably mean to use hexalpha[i] != '\0' (note the single-quotes).
Besides that, you don't see the answer because it's never printed. In most shells you can print the return-value of the last program with $? (on Windows it's %errorlevel%), like this:
echo $?
For example, if I run the program like this:
> a.out
b
> echo $?
11
You see that getchar works correctly, but you don't see the output because the shell doesn't usually print the return-value of a program. Alternatively, you can add a printf-statement at the end of your program. This is recommended anyway because the return-value of main is more commonly used to determine whether the program finished successfully, or not.
printf("%i\n", answer);
return 0;
}

I can read that there *are* chars in a file, but not print them out to another file

So if I say fprintf(output, "hello"); it prints hello a bunch of times so it definitely recognizes there are characters inside. But the file is blank when I say to print c.
How do I get it to print the chars from one file into another?
edit: those declarations above are for the rest of the code but I'm just trying to test the printing for now.
edit: still solving this. Might just use redirection from putty.
To output a character, use the %c format specifier:
fprintf(output, "%c", c);
or you can use fputc() for this job.
I don't know how your compiler implements getc but I suspect the line
int getc(allcrazy);
has something to do with the crazy behavior you are seeing.
With minor changes, your code works just fine. This is what I have that works like a charm.
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *allcrazy;
FILE *output;
allcrazy = fopen("allcrazy.c", "r");
output = fopen("output.c", "w");
int c, readChar;
// STATE state = READING_INPUT;
int errorLine = 0;
// int getc(allcrazy);
while (c = fgetc(allcrazy) != EOF) {
fputc(c, output);
}
return 0;
}
Your primary problem is the insufficient parentheses in this line:
while (c = fgetc(allcrazy) != EOF) {
It assigns 0 or 1 to c, and tries to write Control-A characters to the output file. The code is equivalent to:
while (c = (fgetc(allcrazy) != EOF)) {
You need to use:
while ((c = fgetc(allcrazy)) != EOF) {
This does the assignment before the comparison. Since c is an int, you should be in with a decent chance from here…well, as long as you fix the printing too.
The printf() statement in the body of the loop is also flawed; you don't include a format string. You should use putc(c, output); or fprintf(output, "%c", c); — or you can use fputc(c, output); though I really don't see a need for that here.
As written (fprintf(output, c)), you pass an int where the function expects a character pointer. Your compiler should be complaining about this. If it isn't, you need to turn up the warning levels until it does, or you need to get a better compiler. And you need to heed warnings from your compiler; remember, at this stage, it knows a lot more about C than you do.

Reading Stdin in chunks... (possibly with scanf?)

I have a linux box.
On this linux box, there is a program.
In this program, I have a loop like this:
int num=*"what num needs to be"*;
char proc[num];
int result;
while (1) {
result=scanf("%[^'&']%s",proc);
printf("And proc is: %s\n",proc);
printf("Result counter was: %i\n",result)
if (result == 0) break;
}
scanf("%[^'&'],%s",proc)
printf("post lop result is: %s", proc);
As you may have guessed, stdin contains data I need delineated by the '&' character.
As I'm hoping someone more skilled than me has guessed, the output looks something like:
And proc is: *first delineated section*
Result counter was: 1
And proc is: *first delineated section*
Result counter was: 0
post loop result is: *first delineated section*
I thought that scanf was supposed to consume the part of stdin it has already read. Why isn't it doing this?
Also, FYI: this is being run on a very cheap, slow server. Volume may or may not become more than slight. Efficiency is thus a plus, I'm open to however someone might suggest I do this....
Thanks!
The scanset does not need two single quotes in it — one is sufficient if you want to break on a single quote, but I suspect you only want to stop on &, and the code below assumes that too. Once you've read up to the first &, you need some code to read the &. You need to check the result of scanf() before using the data it returned.
Hence:
int num = 100;
char proc[num];
int result;
while ((result = scanf("%99[^&]", proc)) == 1)
{
printf("And proc is: <<%s>>\n", proc);
printf("Result counter was: %i\n", result);
int c;
while ((c = getchar()) != EOF && c != '&')
;
}
You also need to decide whether newlines mark the end of a field too...if they do, then:
int num = 100;
char proc[num];
int result;
while ((result = scanf("%99[^&\n]", proc)) == 1)
{
printf("And proc is: <<%s>>\n", proc);
printf("Result counter was: %i\n", result);
int c;
while ((c = getchar()) != EOF)
{
if (c != '&' && c != '\n')
{
ungetc(c, stdin);
break;
}
}
}
Note the use of %99[...] to prevent buffer overflows. The angle brackets <<%s>> simply mark the start and end of the string; they make trailing blanks and tabs visible, for example.
The code assumes you have a C99 compiler that allows variable declarations midway through a block of code. If not, move int c; to the top of the loop
The problem is that on the second iteration the scanf can't read the format you gave it (the line read from standard input does not match) and doesn't modify proc. That's also the reason it returns 0: it has successfully read (and thus modified) 0 fields.

Resources