【问题标题】:Programming in C how to output inputted string onto the screen?用C编程如何将输入的字符串输出到屏幕上?
【发布时间】:2015-09-15 05:33:25
【问题描述】:

我试图让我的程序将输入到我的程序中的单词输出到屏幕上。到目前为止,我的程序根据我输入的内容输出随机字符。例如,如果我输入单词 hey,它会在屏幕上输出 %。我该如何解决这个问题以在屏幕上输出单词 hey?我的代码在下面。

#include <stdio.h>
#include<conio.h>

int main(){
    int word;
    char cont;
    for (;;){
        int countword = 0;
        int countpunct = 0;
        printf("\nEnter the String: ");
        while ((word = getchar()) != EOF && word != '\n'){
            if (word == ' ' || word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
                countword++;
            }
            if (word == '.' || word == '?' || word == '!' || word == '(' || word == ')' || word == '*' || word == '&'){
                countpunct++;
            }
        }

        printf("%c", word);

        printf("\nThe number of words is %d.", countword);

        printf("\nThe number of punctuation marks is %d.", countpunct);

        printf("\nContinue? Y/N?");
        scanf("%c", &cont);
        if (cont != 'y' && cont != 'Y'){
            return 0;
        }
    }
}

【问题讨论】:

  • 您没有打印word 的值。使用printf("%c", word);。另外,不需要将其类型设为int
  • 如果您之前没有使用过调试器,现在可能是时候了。逐行执行代码,同时跟踪所有变量及其变化,希望问题会变得清晰。
  • 如果要打印每个字符,请将 printf 移到循环内
  • 有没有办法让我的程序打印在新行上输入的每个单词?

标签: c string loops


【解决方案1】:

您正在使用 &amp;printf()。它将打印变量的地址(而不是它的值)!

改为这样做:

printf("%c", word); // notice there is no &

除此之外,我注意到您的代码中有几处值得一提:

word 被声明为int,但被读取和打印为char。为什么?

【讨论】:

  • 记住getchar 返回一个int。还有那个(char) EOF != (int) EOF
【解决方案2】:

您的while 循环确保word 在退出while 循环时保持EOF\n

while ((word = getchar()) != EOF && word != '\n')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    相关资源
    最近更新 更多