【问题标题】:Programmes won't run on Ubuntu 12.04 and Windows XP程序无法在 Ubuntu 12.04 和 Windows XP 上运行
【发布时间】:2014-06-14 05:55:31
【问题描述】:

在安装了 Eclipse 和 CB 之后,我遇到了几个无法正常启动的项目。我认为这是因为我使用的操作系统,这就是我切换到 Ubuntu 的原因。但是,我尝试运行的某些程序仍然无法正常运行。例如,来自 clc-wiki 的这段代码在按下 Enter 时什么也不输出:

#include <stdio.h>
#define MAXLINE 40 /* maximum input line size */

int getlines(char line[], int maxline);
void copy(char to[], char from[]);

/* print longest input line */
int main()
{
int c;
int len;    /* current line length */
int max;    /* maximum length seen so far */
char line[MAXLINE];     /* current input line */
char longest[MAXLINE];  /* longest line saved here */

max = 0;

while ((len = getlines(line, MAXLINE)) > 0) {
    if (line[len-1] != '\n')
        while ((c = getchar()) != EOF && c != '\n')
            ++len;

    if (len > max) {
        max = len;
        copy(longest, line);
    }
}

if (max > 0) {    /* there was a line */
    printf("Longest line with %d characters:\n", max);
    printf("%s ...\n", longest);
}

return 0;
}

/* getline: read a line s, return length */
int getlines(char s[], int lim)
{
int c, i;

for (i = 0; i < lim-1 && (c = getchar()) != EOF && c != '\n'; ++i)
    s[i] = c;
if (c == '\n') {
    s[i] = c;
    ++i;
}
s[i] = '\0';

return i;
}

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
int i;

i = 0;
while ((to[i] = from[i]) != '\0')
    ++i;
}

如果我们在 XP 中运行它,也会遇到类似的问题。不过,如果我们在 ideone 中编译完全相同的代码,一切都会完美。

gcc 和 g++ 已安装,还有 mingw for Windows。

你能告诉我问题是什么吗?

【问题讨论】:

  • 你能看懂这段代码吗?你知道它的预期输入和输出是什么吗?你知道如何正确运行它吗?
  • 与问题没有真正的关系,但有什么特别的原因让您编写自己的copy 方法而不使用string.hstrcpystrncpy
  • 亲爱的 Lee Duhem, 不幸的是,我不完全理解代码,即我无法自己编写所有代码。我认为输入是我输入的所有内容。如果我在构建项目后(例如在 CB 中)按下运行按钮,我是否可以正确运行它?
  • 亲爱的霸王,我认为这对我来说是一种锻炼。

标签: c eclipse windows ubuntu


【解决方案1】:

此代码在按下 Enter 时不输出任何内容

这是您的代码的正确行为。它被设计为在按下 Enter 时不打印任何内容。

该代码尤其需要文件结束指示。如果您的程序从文件中读取数据(如 ideone 上的情况),文件结束指示或多或少会自动发生。如果您的程序从计算机键盘读取数据(就像您以交互方式运行它时一样),那么您必须提供文件结束指示。

练习您提供的代码:

在 Linux 上,从键盘输入几行不同长度的行,每行后跟 Enter。然后单独输入一行CONTROL-D

在 Windows 上,从键盘输入几行不同长度的行,每行后跟 Enter。然后输入 enter CONTROL-Z 单独一行。

【讨论】:

  • 亲爱的 Rob, 非常感谢您抽出宝贵时间。有用。我真的很抱歉我的直言不讳。
  • @Delly - 不需要道歉。我很高兴我能提供帮助。如果我的答案或任何其他答案满足您的问题,请点击答案旁边的复选标记“接受”它。
猜你喜欢
  • 2014-10-08
  • 1970-01-01
  • 1970-01-01
  • 2014-01-04
  • 1970-01-01
  • 1970-01-01
  • 2012-10-15
  • 2012-08-21
  • 1970-01-01
相关资源
最近更新 更多