Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

c - Unexpected output while reading string from a keyboard

This program is returning something which I'm not able to comprehend. Attached is the screenshot of the O/P simple program to find number of spaces, tabs, etc.

What am I missing?

#include <stdio.h>
#include <string.h>

int main() {
    int count[] = { 0, 0, 0 }; /* 0 is spaces, 1 is tabs and 2 for newline. */
    int string;
    
    printf("Enter the paragraph: 
");
    while ((string = getchar()) != EOF) {
        if (string == ' ')
            count[0]++;
        else if (string == '')
            count[1]++;
        else if (string == '
')
            count[2]++;
    }
    printf("There are %d Spaces.
", count[0]);
    printf("There are %d Tabs.
", count[1]);
    printf("There are %d Newlines.
", count[2]);
    return 0;
}

enter image description here

question from:https://stackoverflow.com/questions/65643911/unexpected-output-while-reading-string-from-a-keyboard

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the screenshot it appears you typed Ctrl-Z to signal the end of file to your program. While this works in legacy systems such as MS/DOS and the Windows terminals, this key combination has a different meaning on unix systems such as linux: it causes the current process to be suspended by its the running shell parent. The process can be resumed later with the fg command.

To signal the end on file on this system, you should type Ctrl-D instead.

Your program should produce the expected result then. The code seems OK, albeit it is quite confusing to name string an int variable that gets a single byte from getchar(). Such a variable is usually named c.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...