使用 do while 循环打印字符串的一个问题和很多疑问

问题描述 投票:0回答:1

我只是尝试打印通过

scanf
函数收到的字符串,我已将循环设置为进一步处理,直到我按
0
终止。

首先我输入了单个字符串,它被正常打印,但另一次我输入了三个字符串 =>

Name1 Name2 Name3
--> 三个字符串被自动打印,就像我在代码后面提到的那样

程序:**

#include <stdio.h>

int main()
{   
    int i; 

    do {
        char str[20];
    
        printf("\nEnter the String: ");   
    
        scanf("%s", str);              // String input
    
        printf("The String is %s", str);     // Print the String
    
        printf("\n\nEnter the Number 1 to restart and 0 to terminate: ");  //Input for loop
    
        scanf("%d", &i);
    
    } while (i != 0);     // while loop
    
    return 0;
}

输出控制台屏幕:

Enter the String: Name

The String is Name

Enter the Number 1 to restart and 0 to terminate: 1     // Normally printed

// I don't what is happening by Entering three strings with space (Below Mentioned)

Enter the String: Name1 Name2 Name3

The String is Name1

Enter the Number 1 to restart and 0 to terminate: 

Enter the String: 

The String is Name2

Enter the Number 1 to restart and 0 to terminate: 

Enter the String: 

The String is Name3

Enter the Number 1 to restart and 0 to terminate: 0

...程序结束,退出代码为 0 按 ENTER 退出控制台。

c scanf do-while conversion-specifier
1个回答
0
投票

如果你想输入一个包含多个由空格分隔的单词的字符串,那么不要调用

scanf

scanf("%s", str);

scanf(" %19[^\n]", str);

注意格式化字符串中的前导空格。它允许跳过由于按回车键而存储在输入缓冲区中的换行符

'\n'
。否则可以读取空字符串。

至于你的代码然后由于输入缓冲区包含三个输入的字符串然后这个调用

scanf("%d", &i);

整数在读取字符串之间失败,因为输入缓冲区包含字母而不是整数。

在读取所有三个字符串之后,才会调用 scanf,等到您输入一个数字。

© www.soinside.com 2019 - 2024. All rights reserved.