我一直在尝试编译一个从 .data 文件接收数据的 C 程序。不幸的是,我总是收到以下消息:input.dat.2:1:error: 预期标识符或“(”在数字常量之前我正在使用 2014 版的 Ubuntu Linux。实际上,这是我在 Linux 环境中的第一个程序。这是我大学的家庭作业。相同的程序适用于 Windows dev-C++!这是程序:
#include <stdio.h>
#include "input.dat"
#define NUM_NODES 100
#define NONE 9999
#include<csdl_queue.h>
#include<cdsl_deque.h>
#include<cdsl_dyn_array.h>
struct _NODE
{
int iDist;
int iPrev;
};
typedef struct _NODE NODE;
struct _QITEM
{
int iNode;
int iDist;
int iPrev;
struct _QITEM *qNext;
};
typedef struct _QITEM QITEM;
QITEM *qHead = NULL;
int AdjMatrix[NUM_NODES][NUM_NODES];
int g_qCount = 0;
NODE rgnNodes[NUM_NODES];
int ch;
int iPrev, iNode;
int i, iCost, iDist;
void print_path (NODE *rgnNodes, int chNode)
{
if (rgnNodes[chNode].iPrev != NONE)
{
print_path(rgnNodes, rgnNodes[chNode].iPrev);
}
printf (" %d", chNode);
fflush(stdout);
}
void enqueue (int iNode, int iDist, int iPrev)
{
QITEM *qNew = (QITEM *) malloc(sizeof(QITEM));
QITEM *qLast = qHead;
if (!qNew)
{
fprintf(stderr, "Out of memory.\n");
exit(1);
}
qNew->iNode = iNode;
qNew->iDist = iDist;
qNew->iPrev = iPrev;
qNew->qNext = NULL;
if (!qLast)
{
qHead = qNew;
}
else
{
while (qLast->qNext) qLast = qLast->qNext;
qLast->qNext = qNew;
}
g_qCount++;
}
void dequeue (int *piNode, int *piDist, int *piPrev)
{
QITEM *qKill = qHead;
if (qHead)
{
*piNode = qHead->iNode;
*piDist = qHead->iDist;
*piPrev = qHead->iPrev;
qHead = qHead->qNext;
free(qKill);
g_qCount--;
}
}
int qcount (void)
{
return(g_qCount);
}
int dijkstra(int chStart, int chEnd)
{
for (ch = 0; ch < NUM_NODES; ch++)
{
rgnNodes[ch].iDist = NONE;
rgnNodes[ch].iPrev = NONE;
}
if (chStart == chEnd)
{
printf("Shortest path is 0 in cost. Just stay where you are.\n");
}
else
{
rgnNodes[chStart].iDist = 0;
rgnNodes[chStart].iPrev = NONE;
enqueue (chStart, 0, NONE);
while (qcount() > 0)
{
dequeue (&iNode, &iDist, &iPrev);
for (i = 0; i < NUM_NODES; i++)
{
if ((iCost = AdjMatrix[iNode][i]) != NONE)
{
if ((NONE == rgnNodes[i].iDist) ||
(rgnNodes[i].iDist > (iCost + iDist)))
{
rgnNodes[i].iDist = iDist + iCost;
rgnNodes[i].iPrev = iNode;
enqueue (i, iDist + iCost, iNode);
}
}
}
}
printf("Shortest path is %d in cost. ", rgnNodes[chEnd].iDist);
printf("Path is: ");
print_path(rgnNodes, chEnd);
printf("\n");
}
}
int main() {
int i,j,k;
FILE *fp;
fp=fopen("input.dat","r");
/* open the adjacency matrix file */
/* make a fully connected matrix */
for (i=0;i<NUM_NODES;i++) {
for (j=0;j<NUM_NODES;j++) {
/* make it more sparce */
fscanf(fp,"%d",&k);
AdjMatrix[i][j]= k;
}
}
/* finds 10 shortest paths between nodes */
for (i=0,j=NUM_NODES/2;i<20;i++,j++) {
j=j%NUM_NODES;
dijkstra(i,j);
}
fclose(fp);
exit(0);
}
该程序可能有效,因为它是老师授予我们的。input.dat 仅由数字组成。我猜想 Ububtu 系统在某种程度上应该对此负责。为什么编译过程会失败?如果有人能帮助我,我将不胜感激!
答案1
从程序中删除第二行:
#include "input.dat"
此行将导致编译器读取输入文件。正如您所解释的那样,输入文件不是 C 代码,因此不会编译。
但是,输入文件不会包含在您的程序中,而是在运行时从文件系统读取。
如果您说相同的程序在 Windows 上运行良好,那么您的意思是完全相同的代码在 Windows 上运行良好吗?这确实让我很惊讶,因为无论您在哪个平台上,只有数字不是 C。