gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:31:21 26 4
gpt4 key购买 nike

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

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com