使用whil​​e循环scanf函数功能

使用whil​​e循环scanf函数功能

本文介绍了使用whil​​e循环scanf函数功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图格式化空格分隔用户输入一个编程任务。

I am attempting to format a space-delimited user input for a programming assignment.

基本上,输入由前pressions任意数量的

Essentially, the input consists of an arbitrary number of expressions

→整数整数整数整数ç整数整数整数

例如: L 1 1 5 7的C 4 5 3

到目前为止,我已经成功地提取依赖于初始角色的整数,并且可以通过字符串使用scanf函数功能迭代:

So far, I've managed to extract the integers depending on the initial character, and can iterate through the string using the scanf function:

char a;
while(scanf("%c", &a) == 1){
    if(a == 'C'){
        int inputX, inputY, inputR;
        scanf("%d %d %d", &inputX, &inputY, &inputR);
        printf("%d %d %d\n", inputX, inputY, inputR);
    }
    else if(a == 'L'){
        int x1, y1, x2, y2;
        scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
        printf("%d %d %d %d\n", x1, y1, x2, y2);
    }
}

不幸的是,虽然这输出所需的整数,循环(和用户输入提示)不会终止。

Unfortunately, although this outputs the desired integers, the loop (and user input prompt) doesn't terminate.

可能有人请赐教,为什么发生这种情况?

Could someone please enlighten me as to why this is happening?

推荐答案

这是因为 \\ n 是永远存在的,以 scanf函数(% C,&安培;一)== 1 总是正确的结果。
更改

This is because \n is always there to make scanf("%c", &a) == 1 always true.
Change your

while(scanf("%c", &a) == 1)

while(scanf(" %c", &a) == 1)
     //      ^space before format specifier.

%C A空间会吃了这个 \\ n scanf函数掉队(上pressing 输入)。

A space before %c will eat up this \n left behind by scanf (on pressing ).

这篇关于使用whil​​e循环scanf函数功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 19:20