【问题标题】:not output after program was run?程序运行后不输出?
【发布时间】:2015-05-22 19:56:16
【问题描述】:

我很困惑为什么我的程序运行不好。我使用 PuTTY 通过我的 Windows PC 连接到服务器。它总是工作正常,但我相信有些奇怪的事情正在发生。 这是 identify.c 的代码:

#include <stdio.h>
#include <ctype.h>

int main()
{
    while(1)
    {
        char word[256];
        int i;
        int validity = 1;

        scanf("%s", word);

        for(i=0; word[i]!='\0'; i++)
        {
            if(i == 0)
            {
                /* First character should only be underscore or a letter */
                if(word[i]!= '_' && !isalpha(word[i]))
                {
                    validity = 0;
                    break;
                }

            }
            else
            {
                /* Rest can be Alpha-numerics or underscore */
                if(word[i]!= '_' && !isalnum(word[i]))
                {
                    validity = 0;
                    break;
                }
            }

        }

        if(validity)
            printf("valid\n");
        else
            printf("invalid\n");
    }

    return 0;
}

这是用于测试名称是否是可能的标识符名称的输入文件。身份测试.txt:

name

name2

2name

_name

__name

na_me

@name

na-me

然后我使用 FileZilla 将这两个文件上传到我的服务器。

然后我执行以下命令使 identify.c 可执行:

gcc identify.c -o identify

已创建可执行文件。 然后我运行以下命令:

identify <identifytest.txt >output.txt

然后创建的 output.txt 为空。

任何想法为什么?在过去的 2 天里,我一直为此发疯,不知道发生了什么。

【问题讨论】:

  • 这个程序什么时候终止?
  • @simon 正要问同样的问题... :-)
  • 第 1 步:限制输入长度。更改为scanf("%255", word); 2) 检查scanf()if (1 != scanf("%255", word)) break;的结果
  • 您编辑了问题以删除所有代码。形式不好。我帮你恢复了。

标签: c input output executable


【解决方案1】:

std 输入关闭时必须打破无限循环:

if (scanf("%s", word) == EOF) break;

您也可以刷新标准输出以强制将结果写入输出文件:

fflush(stdout);

【讨论】:

  • 我将其更改为 !feof(stdin) 但现在它创建了一个包含数百万个答案(真、假)的输出文件
【解决方案2】:

您的程序没有退出条件。我只加了一行

if(i == 0)
    {
    if (word[i] == '!') return 0;       // <--- added this line
    ...

然后是命令(和你的类似)

test <test.txt >output.txt

在读取"!" 行后将预期结果写入output.txt

【讨论】:

  • 我做了这个精确的修改,它现在仍然创建了一个包含数百万结果的输出文件:/
  • 你改变了问题。它说“创建的 output.txt 是空的。”。现在你说“数百万个结果”。是哪个?
  • 之前没有输出,现在编辑后显示了很多答案。
  • 你把问的问题改成了空,我把它回滚了。否则毫无意义。
猜你喜欢
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 2016-02-13
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多