c - 如何在C中解析一行整数

标签 c parsing

我想对以下测试文本文件中的每个整数进行非常基本的读取。

1 2 3 4 5
6 7 8 9 10

但是在我正确打印第一行后,以下代码无限打印 1。

FILE* f;
uint32_t current_row = 0;
uint32_t current_col = 0;
char line[1024];
int value; // issues with printing uint32_t right now

// Open the file
f = fopen("blah.txt", "r");
if (f == NULL) {                                                               
  fprintf(stderr, "file could not be opened.\r\n");                    
  exit(ERROR_FILEPATH);                                                        
}

// Read in each row
while (NULL != fgets(line, sizeof(line), f)) {
  printf("%d: %s\r\n", current_row, line);

  // Read in each integer in the current row 
  while (sscanf(line, "%d", &value) {
    printf("%d\t", value);
    // TODO: How to read a single integer in at a time?
    current_col++;
  }

  current_col = 0;
  current_row++;
}

// Close the file                                                              
if (fclose(f)) {                                                      
  fprintf(stderr, "file could not be closed.\r\n");                      
  exit(ERROR_FILECLOSE);                                                       
}

最佳答案

而不是:

  // Read in each integer in the current row 
  while (sscanf(line, "%d", &value) {
    printf("%d\t", value);
    // TODO: How to read a single integer in at a time?
    current_col++;
  }

就我个人而言,我不喜欢“scanf”函数系列:

  // Read in each integer in the current row 
  char *cp = line;
  while(*cp && *cp != '\n') 
    {
    /* skip leading white space. */
    while(isspace(*cp))
       ++cp;

    /* Read the next number. */   
    value = strtol(cp, &cp, 10);
    printf("%d\t", value);

    current_col++;
    }

关于c - 如何在C中解析一行整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23976711/

相关文章:

c - Malloc 在为整数分配空间时表现异常

c - 我如何检查 C 中的文件是否为空?

c++ - 如何使用Lua5.1 柠檬语法?

postgresql - 从字符串中解析间隔的最佳方法是什么?

c++ - 逐行读取文件并解析为 vector C++ 中的大量整数

解析 Bison/YACC .y 文件而不解析所有 C 语言

c - 在c中打印新的字符数组(奇怪的符号)

c - 在C编程中处理客户端-服务器套接字中的ctrl+c

c - 为什么 "hello"在 boolean 条件下评估为真?

python - PathLike 对象中的 __fspath__() 函数