我在C编程语言中遇到代码的某个方面有问题。这是手头的问题。我必须读取格式如下的文件:
q 99
z 8
q 4
每行以q或z开头,后跟一个制表符,后跟一个数字。我想只存储链接列表中第q行开头的数字。
我能够隔离以q开头的行,但我的代码将值99分成两个独立的节点9和9.我不知道如何解决这个问题。
任何建设性的帮助都会很棒,而且要善良,我是C语言的新手!
// Beginning of code reads the file in, and provides structure and
// function declarations
struct node *start = NULL;
char w;
while((w = fgetc(filep))!= EOF ) //filep is pointer to the file
{
if(w=='z')
break;
else if(isdigit(w))
push(&start, w); //push function creates the nodes
}
// rest of code has function definitions of push and print, creating
// and printing the linked list
答案 0 :(得分:2)
您目前正逐字逐句地阅读。 "99"
由两个字符组成。
对这个特定问题的一个简单解决方法是使用一个旨在解析格式化输入的函数,如scanf()
。
以下是如何使用它的示例:
while (true) {
char w;
int v;
int count = scanf(" %c %d", &w, &v);
if (count != 2)
break;
if (w == 'q')
push(&start, v);
}
请注意,在格式字符串中,我包含了一个前导空格。这将确保在我们到达%c
之前,我们使用任何前导空格。这个空格将包括前一行的尾随换行符。