如何从fgets中检测新行然后将其转换为'\ 0'?

时间:2013-09-07 02:02:14

标签: c compiler-errors fgets

我需要检测输入是否为新行。之后,我需要将其转换为'\0'。这是我的代码:

void number()
{
    printf(LEV3"Student No. (20XXXXXXX):\t");
    int x=0, i=0;
    fgets(studno[i], LEN, stdin);
    if('\n'==studno[LEN-1])
        {
        [LEN-1]='\0';
        }
    x = atoi(studno[i]);
    if (((x/10000000)>=21||(x/10000000)<=19))
    {
        printf("ERROR: Invalid Student Number. Format should be 20XXXXXXX.\n");
        number();
    }

    i++;
}

我该怎么办?我总是在这段代码中遇到编译器错误。

3 个答案:

答案 0 :(得分:0)

您显示的代码至少有几个语法错误。

  1. printf(LEV3"Student No. ...中的字符串有迷路“LEV3”。 这应该是格式字符串的一部分还是它是什么?

  2. 在检查换行符的if中,您保留了字符串名称 尝试在字符串中设置空值时。代替 [LEN-1] = '\0';您应该studno[LEN-1] = '\0';

  3. 这个函数(number)自称...... Eek!你是说这个函数是递归的吗?目前还不清楚目的是什么。您的本地变量i正在递增,就好像下一次调用number会看到它一样,但它不会,因为它是一个局部变量。对于这样的事情,你只需要一个循环,而不是递归。

  4. 因此,使用@ Gangadhar的建议,您的代码最终应该看起来像这样阅读该行。我将留下其余的时间让你更新,因为我不确定你对i等的意图是什么,而你还没有解释输入的格式是什么。我假设studno是一个char指针数组,但你没有显示它。

    void number()
    {
        printf("Student No. (20XXXXXXX):\t");
        int x = 0, i = 0;
        fgets(studno[i], LEN, stdin);
    
        if ('\n' == studno[i][strlen(studno)-1])
        {
            studno[i][strlen(studno)-1] = '\0';
        }
    
        ...
    }
    

答案 1 :(得分:0)

您发布的代码存在许多问题,以及下面的代码,但我认为它可以回答您的问题。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define LEV3 "\t\t\t"
#define LEN 30
char studno[LEN+1];

void number()
{
  printf(LEV3"Student No. (20XXXXXXX):\t");
  fgets(studno, LEN, stdin);

  int x = atoi(studno);
  if (((x/10000000)>=21||(x/10000000)<=19))
  {
    printf("ERROR: Invalid Student Number. Format should be 20XXXXXXX.\n");
    number();
  }

  int l = strlen(studno);
  if('\n'==studno[l-1])
  {
    studno[l-1]='\0';
  }
}

int main(int argc, char* argv[]) {
  number();
  printf("'%s'", studno);
  return 0;
}

答案 2 :(得分:0)

使用fgets(buffer,...)后,
1.缓冲区以第一次出现\n然后是\0结束 2.它只能以\0而不是\n结束 3.如果没有可用的输入或I / O错误,缓冲区可以保持不变。

char buffer[N];
if (fgets(buffer, sizeof(buffer), stdin) == NULL) {
  ; // handle no data read as file I/O error or EOF
}
else {
  size_t len = strlen(buffer);
  // Be sure to check for len > 0
  if ((len > 0) && (buffer[len - 1] == '\n')) {
    buffer[--len] = '\0';
  }
  // use buffer
}
相关问题