忽略whitepace用的fscanf或与fgets? [英] Ignoring whitepace with fscanf or fgets?

查看:138
本文介绍了忽略whitepace用的fscanf或与fgets?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有什么办法可以忽略不管是用的fscanf或与fgets功能空白。我的文本文件,有可能会或可能不会被一个空格隔开的每个线两条字符。我需要阅读这两个字符,并把每一个在不同的阵列。

 文件=的fopen(的argv [1],R);
如果((文件= FOPEN(的argv [1],R))== NULL){
    的printf(\\ n错误打开文件);
}
而(的fscanf(文件%S,STR)!= EOF){
    的printf(\\ N%的,STR);
    vertexArray [I] .label = STR [0];
    DIRC [I] = STR [1];
    我+ = 1;
}


解决方案

使用空间()中的fscanf格式,使其读取和丢弃空白输入,直到它找到一个非空白字符,让输入非空白字符作为要读取的下一个字符。所以,你可以做这样的事情:

 的fscanf(文件,); //跳过空白
GETC(文件); //获取非空白字符
的fscanf(文件,); //跳过空白
GETC(文件); //获取非空白字符

 的fscanf(文件%C%C,&安培; CHAR1,&安培; CHAR2); //读2个非空白字符,每跳过之前的任何空白

I was wondering if there is any way to ignore whitespace with either the fscanf or fgets function. My text file has two chars on each line that may or may not be separated by a space. I need to read the two chars and place each one in a different array.

file = fopen(argv[1], "r");
if ((file = fopen(argv[1], "r")) == NULL) {
    printf("\nError opening file");
}
while (fscanf(file, "%s", str) != EOF) {
    printf("\n%s", str);
    vertexArray[i].label = str[0];
    dirc[i] = str[1];
    i += 1;
}

解决方案

Using a space (" ") in the fscanf format causes it to read and discard whitespace on the input until it finds a non-whitespace character, leaving that non-whitespace character on the input as the next character to be read. So you can do things like:

fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character
fscanf(file, " "); // skip whitespace
getc(file);        // get the non-whitespace character

or

fscanf(file, " %c %c", &char1, &char2); // read 2 non-whitespace characters, skipping any whitespace before each

这篇关于忽略whitepace用的fscanf或与fgets?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆