简体   繁体   English

如何修改我的代码以使用 strtol() 而不是 scanf() 仅读取前两个整数?

[英]How do I modify my code to use strtol() instead of scanf() to read in first two ints only?

My current code seems to work fine on DOS but not on Unix, and I need to make it work on both.我当前的代码似乎在 DOS 上运行良好,但在 Unix 上运行良好,我需要让它同时运行。 From what I have found so far, it seems I should use strtol().从我目前的发现看来,我应该使用 strtol()。 However, I cannot seem to figure out how to get strtol() to get only the first two integers.但是,我似乎无法弄清楚如何让 strtol() 只获得前两个整数。

The input is a text file that looks like this:输入是一个文本文件,如下所示:

45x7
(1,0)
(10,2)

And I need the output to be "There are 45 rows and 7 columns."我需要 output 是“有 45 行和 7 列”。

This is my current code:这是我当前的代码:

int rows=0, columns=0;
scanf("%d%*c%d%*c", &rows, &columns);
printf("There are %d rows and %d columns.", rows, columns);
return 0;

I do not want to discard the remaining text file as I will need to process that as well.我不想丢弃剩余的文本文件,因为我也需要处理它。

Here's one way of using fgets and strtol .这是使用fgetsstrtol的一种方法。 It is admittedly more verbose than the scanf solution.无可否认,它比scanf解决方案更冗长。

int rows=0, columns=0;
char *endp;
char firstline[100];
if(fgets(firstline, sizeof(firstline), stdin) == NULL) {
    fprintf(stderr, "premature EOF\n");
    exit(1);
}
rows = strtol(firstline, &endp, 10);
if(*endp != 'x') {
    fprintf(stderr, "syntax error\n");
    exit(1);
}
columns = strtol(endp + 1, &endp, 10);
if(*endp != '\n') {
    fprintf(stderr, "syntax error\n");
    exit(1);
}
printf("There are %d rows and %d columns.\n", rows, columns);

The key is that strtol 's second argument is a pointer to a pointer which is filled in with a pointer to the first character strtol didn't use.关键是strtol的第二个参数是一个指向指针的指针,该指针用指向strtol未使用的第一个字符的指针填充。 That is, when you pass the string 45x7\n to the first strtol call, it returns 45 , and sets endp to point to the x .也就是说,当您将字符串45x7\n传递给第一个strtol调用时,它会返回45 ,并将endp设置为指向x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM