我希望扫描文件,但它有两种不同的结构。
文件:
ParisRoubaix "Marco MARCATO" 33 UAD ITA 26 5:43:31
ParisRoubaix "Sam BEWLEY" 30 ORS NZL DNF 0
代码:
fscanf(filepointer, " %[a-zA-Z] %[a-zA-Z\" ] %d %[a-zA-Z] %[a-zA-Z] %[a-zA-Z1234567890]", )
但我不知道如何完成整理时间 有两个结局
所以我要扫描司机的时间,我该怎么做? < 3
答案 0 :(得分:0)
这是一种方式:
@RunWith(Arquillian.class)
public class EjbTest {
@Deployment(name = "test.jar")
public static JavaArchive createDeployment() {
// explicit archive name required until ARQ-77 is resolved
return ShrinkWrap.create(JavaArchive.class, "test.jar")
.addPackage(Book.class.getPackage())
.addPackage(BookEJB.class.getPackage())
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
.addAsManifestResource("ejb-jar.xml");
}
@Test
public void convertThePriceOfAnItemTest() throws Exception {
Item book = new Item("Cars", 10.0f, "Book of cars");
book.setCurrency("Dollars");
book= itemEJB.convertPrice(book);
assertEquals("Price should be 12.5 * 0.9", Float.valueOf(11.25f), book.getPrice());
}
}
这里,了解ret变量是很重要的:
注意:优良作法是编写 int ret,hour,min,sec;
while(ret = fscanf(filepointer, " %[a-zA-Z] %[a-zA-Z\" ] %d %[a-zA-Z] %[a-zA-Z] %[a-zA-Z0-9] %[0-9] : %[0-9] : %[0-9]", ... , &hour, &min , &sec ) )
{
if(ret == EOF)
{
break;
}
else if(ret == 9)
{
// Time is there and it is stored in hour, min and sec
}else if(ret == 7)
{
// 0 is in the line and 0 is stored in hour
}else
{
// error in reading the file.
printf("%d",ret);
break;
}
}
而不是%[a-zA-Z0-9]
答案 1 :(得分:0)
以下是一个用于处理您的文件的程序。通常,%s
表示字符串。在使用scanf进行解析时,接受自己接受的内容会更好。对您已阅读的输入执行规则比理解为什么scanf返回意外的小值更容易。此外,如果您的规则比#34;仅大写"更复杂,您很快就会想要正则表达式(3)。
在您的情况下,您可以使用一种模式解析时间。如果fscanf返回9个元素,那么你就是实时的;如果是7,你就得零。还有别的错误。如果您的输入有许多行,您可能需要跟踪错误消息的行号。 :-)
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
int
main( int argc, char *argv[] ) {
char id[64], name[64], thing2[8], thing3[8], seconds[8];
int ret, thing1, hour=25, min, sec;
FILE *input;
if( argc < 2 ) {
errx(EXIT_FAILURE, "filename?");
}
if( (input = fopen(argv[1], "r")) == NULL ) {
err(EXIT_FAILURE, "could not open %s", argv[1]);
}
while( (ret = fscanf(input, "%s %[a-zA-Z\" ] %d %s %s %s %d:%d:%d",
id, name, &thing1, thing2, thing3, seconds,
&hour, &min, &sec)) != EOF ) {
switch(ret) {
case 0:
errx(EXIT_FAILURE, "nothing' doin'");
break;
case 9:
printf("time is %d:%d:%d\n", hour, min, sec);
break;
case 7:
printf("%s in %d seconds\n", seconds, hour);
break;
default:
errx(EXIT_FAILURE, "found %d elements", ret);
break;
}
}
if( ferror(input) ) {
err(EXIT_FAILURE, "scan trouble"); // error in reading the file.
}
return EXIT_SUCCESS;
}
输出:
$ ./time input
time is 5:43:31
DNF in 0 seconds