Scanf(“%[^ \ n]”)不在循环内使用数组字符串(Scanf(“%[^\n]”) not working with array string inside loop)

编程入门 行业动态 更新时间:2024-10-17 09:49:50
Scanf(“%[^ \ n]”)不在循环内使用数组字符串(Scanf(“%[^\n]”) not working with array string inside loop)

我用C编写了这段代码。我需要解决一个问题,我必须输入5行字符串,包括空格。 这个程序只给我输出所有5行字符串,包括空格。 通过空格我的意思是在输入上我可以放置空格之前和char或任何char之后。 这就是我编写这段代码的原因,但我无法理解为什么它不起作用。

#include<stdio.h> int main() { char str[5][100]; for(int i=0;i<5;i++) { scanf("%[^n\]",str[i]); } for(int j=0;j<5;j++) { printf("%s\n",str[j]); } return 0; }

我试过只使用

scanf("%s",str[i]);

但是它忽略了输入中的所有空格并修剪输出。 我还试着用

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

这一次好一点,但是在示例输入之类的任何字符之前忽略了所有空格。

Robin Islam // output showing Robin Islam // should show Robin Islam

我只是想让这个程序允许每个我的意思输出上的空格应该显示与输入相同而不忽略空格。 有人请帮帮我。 尝试了许多方法,但不知道如何使其工作或如何......请帮助

谢谢,罗宾

I've written this code in C. I need to solve a problem and there I'll have to input 5 line string including whitespace. This program will just give me output of all 5 line string including whitespace. By white space I mean on input I can put space before and char or after any char. That's why I've written this code but I can't understand why it's not working.

#include<stdio.h> int main() { char str[5][100]; for(int i=0;i<5;i++) { scanf("%[^n\]",str[i]); } for(int j=0;j<5;j++) { printf("%s\n",str[j]); } return 0; }

I tried to use only

scanf("%s",str[i]);

but then it's ignoring all whitespace inside the input and trimming the output. Also I tried to use

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

this time little better but it's ignoring the all white space before any character a example input is like.

Robin Islam // output showing Robin Islam // should show Robin Islam

I just want to make this program to allow whitespace on every I mean output should show the same as input without ignoring space. Someone please help me. Tried lot's of way but don't know how to make it works or how......Help please

Thanks, Robin

最满意答案

#include<stdio.h> #include<stdlib.h> int main() { char str[5][100]; for(int i=0;i<5;i++) { fgets(str[i],100,stdin); } for(int j=0;j<5;j++) { printf("%s\n",str[j]); } return 0; } #include<stdio.h> #include<stdlib.h> int main() { char str[5][100]; for(int i=0;i<5;i++) { fgets(str[i],100,stdin); } for(int j=0;j<5;j++) { printf("%s\n",str[j]); } return 0; }

更多推荐

本文发布于:2023-08-06 23:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1456712.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   Scanf   working   loop

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!