gpt4 book ai didi

c - 从用户处获取字符串: Problem with Getting unwanted words into the array

转载 作者:行者123 更新时间:2023-11-30 16:27:33 25 4
gpt4 key购买 nike

当我尝试编写此代码时:

int main(){
/*1.*/char A[16];
/*2.*/char B[16];
/*3.*/char C[16];
/*4.*/scanf(" %15[^\n]",A);
/*5.*/scanf(" %15[^\n]",B);
/*6.*/scanf(" %15[^\n]",C);
例如,在第 4 行之后,我从用户那里得到的输入是:“aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa”(30*a)。因此,数组 A 获取输入:“aaaaaaaaaaaaaaa”(15 次),当我到达第 5 行时,它跳转到第 6 行,数组 B 获取输入:“aaaaaaaaaaaaaaaa”(15 次)。如何防止这种情况发生?并允许用户将他的输入插入到数组 B 中?

最佳答案

您可以吃掉这些字符,直到 \n

为此,您可以使用 %*[\n] 规范。

其中 %*[\n] 规范读取并忽略字符,直到到达 \n

示例:

scanf(" %15s%*[^\n]",A);
scanf(" %15s%*[^\n]",B);
scanf(" %15s%*[^\n]",C);

关于c - 从用户处获取字符串: Problem with Getting unwanted words into the array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52692070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com