fgets给了我随机的大号

时间:2015-05-13 23:18:27

标签: c

这是我的代码,我不知道如何在fgets之后使用scanf所以我在第26行也使用fgets,但每次使用它时,它给了我大号(ex.2752100),但我写了2。

为什么要这样做?

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
  char veta[100];
  int line = 1;//tell what line it is on
  int found = 0;
  char a[100];//put the characters of the line into here
  char b[100];
  char linesearch[10];//the line you are looking for
  FILE *file;//the file pointer
  file = fopen("text.txt","r");//point the file
  if (file == NULL)
  {
    printf("file does not exist or doesn't work\n");
    return 0;
  }

  printf("Ahoj, naucim te psat snadno a rychle! \n");
  printf("Vyber si uroven slozitosti od 1 do 10:\n");
  //scanf("%d", &linesearch);
  fgets(linesearch,10,stdin);
  printf("\nHledam uroven %d ...\n\n",linesearch);

编辑:

我有另一个问题:

while(fgets(a,100,file))
{
if(x == line)
{
found = 1;
printf("level %d found,level %d say: %s",x,x,a);
}
else
printf("reading level: %d\n",line );
line++;
}


printf("\nwrite your string as fast as you can!!");
fgets(veta,40,stdin);

if (strcmp(veta,a) == 0)
{
    printf("\nwell done!!!!\n");
}
else
{
    printf("\nwrong!!!!\n");
    printf("%s", a);
    printf("%s", veta);
}

我有小的感情(前我喜欢我的妈妈,她喜欢我等)我想将我的文字与文件中的文字进行比较,如果我写得好,我会得到答案。奖励积分,如果它告诉我我做了多少错误将是强大的!。

3 个答案:

答案 0 :(得分:2)

fgets()函数从输入中读取字符数据。要将此字符数据转换为整数,请使用atoi()或类似函数。

fgets(linesearch, 10, stdin);
int x = atoi(linesearch);
printf("\nHledam uroven %d ...\n\n",x);

您的printf语句正在打印linesearch数组的地址,这似乎是一个随机的大数字。

答案 1 :(得分:0)

如果你想从stdin读取一个char数组,使用scanf()然后打印为int:

scanf("%s", linesearch); // e.g. reads 1234 into array linesearch[].
printf(" %s ...\n\n",linesearch); // Prints string in array linesearch[].
printf(" %p ...\n\n",linesearch); // Prints base address of linesearch[].

int iNum = atoi(linesearch); // Converts string "1234" to number 1234.
printf(" %d ...\n\n",iNum); // Prints the converted int.
iNum++; // Can perform arithmetic on this converted int.

答案 2 :(得分:0)

您从printf获得了一个很大的数字,因为您在格式中使用了%d。该数字是字符数组的内存地址。要打印字符数组,请将格式更新为%s