【发布时间】:2015-07-23 23:06:53
【问题描述】:
我的 firstCheck() 函数有问题。我将在下面用我当前的代码直接解释。我用我所有的 C++ 知识编写了这个程序。
firstCheck() 函数无法正常工作。在 readFile() 函数中,我已成功地将给定文件中的文本逐行拆分为数组。 然后 firstCheck() 应该获取该数组“myString”并读取第一个字符串,直到出现“”(基本上是第一个单词/字符/等),以便我可以评估它。
我很确定我的问题是这部分。由于“stdin”,程序似乎停止并等待我假设的输入什么是实现这个sn-p的更好方法?
while(strcmp(fgets(item.myString, sizeof item.myString, stdin), "" ) != 0 )
{ myWord[s] = strdup(item.myLines[s]); }
我应该改用 scanf() 吗?有人告诉我使用 gets() 是不好的做法,所以我改用 fgets()
Assem.c
#include "assem.h"
int readFile(FILE *file, struct assem *item)
{
size_t i =0;
item->counter = 0; //this is sort of the constructor, if you will.
size_t maxLines = sizeof item->myLines / sizeof *item->myLines; //breaks down text file into line by line
while(i < maxLines && fgets(item->myString, sizeof item->myString, file)) //and stores them into "myLines array"
{
item->myLines[i] = strdup(item->myString);
i++;
item->counter++;
}
return 0;
}
void printFile(struct assem item) //just printing things..prints it with a new line in front
{
printf("\n");
for(int s = 0; s < item.counter; s++)
{
printf("%s\n", item.myLines[s]);
}
printf("\n");
}
int firstCheck(struct assem item)
{
char *myWord [7] = {NULL};
for(int s = 0; s < item.counter; s++)
{
while(strcmp( fgets( item.myString, sizeof item.myString, stdin ), " " ) != 0 )
{
myWord[s] = strdup(item.myLines[s]);
}
}
for(int s = 0; s < item.counter; s++)
{
printf("%s\n", myWord[s]);
}
return 0;
}
“汇编.h”
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct assem
{
char myString[101]; //buffer
char *myLines[20]; //this will store the lines from a text file..up to 20 lines
int counter; //counter for number of lines
//printing stuff...prints file directly from whats STORED IN THE ARRAY
};
int readFile(FILE *FileToBeRead, struct assem *item); //takes in the file that needs to be read and splits it into lines
int firstCheck(struct assem item);
void printFile(struct assem item);
“main.c”
#include "Assem.c"
int main()
{
struct assem test;
FILE *mips;
mips = fopen("/home/rpf0024/cse2610/Program1/mips.asm", "r");
readFile(mips, &test);
printFile(test);
firstCheck(test);
fclose(mips);
return 0;
}
【问题讨论】:
-
输入文件和预期输出是什么?
-
据我所知,您很可能试图将 > 7 个
char*填充到本地数组myWords中。您的item.counter最高可达 20。 -
一句话——“调试器”
-
1)。能否给我们一个小输入的执行结果,比如一个 3 行的 asm 文件? 2)。要验证您的假设是否“因为”stdin“”,您可以尝试将较长的 while 语句分成更小的步骤,看看它是在 stdin 上等待还是在无限 while 循环中运行。然后您可能会获得有关可能存在的问题的更准确信息。
标签: c arrays string function pointers