使用C语言的数组打印字符?
我试图使用以下代码扫描和打印数组的字符,但输入字符与输出字符
#include <stdio.h>
int main() {
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
for (i = 0; i < n; i++) {
scanf("%c", &s[i]);
}
for (i = 0; i < n; i++) {
printf("%c", s[i]);
}
return 0;
}
输出
enter the value of n:
5
start entering the characters:
ABCDE(scanf values)
ABCD(printf values)
任何人都可以澄清我的疑问,为什么输出与输入不匹配
I tried to scan and print the characters of array using below code but input characters are not matching with output characters
#include <stdio.h>
int main() {
char s[10];
int i, n;
printf("enter the value of n:\n");
scanf("%d", &n);
printf("start entering the characters:\n");
for (i = 0; i < n; i++) {
scanf("%c", &s[i]);
}
for (i = 0; i < n; i++) {
printf("%c", s[i]);
}
return 0;
}
OUTPUT
enter the value of n:
5
start entering the characters:
ABCDE(scanf values)
ABCD(printf values)
Can anyone please clarify my doubt why is the output not matching with input
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于您想将数据读取到具有“ scanf”的字符数组中,因此您可能可以改为引用字符串标识符并简化内容。以下是对您的代码进行的一些调整,这些调整仍然输入数据并将其重新打印出来。
该程序只是一次在完整的字符串中扫描而不是字符。另外,我包括“&lt; string.h&gt; file,以便使用诸如“ strlen”(获取字符串的长度)之类的函数为代码提供更鲁棒性。进入
。
Since you are wanting to read data into a character array with "scanf" you probably could just reference the string identifier instead and simplify things. Following are a few tweaks to your code that still inputs the data and prints it back out.
The program just scans in the complete string instead of a character at a time. Also, I included the "<string.h> file so as to use functions such as "strlen" (get the length of the string) to provide a bit more robustness to the code. Running the program netted the same character set that was entered.
You might give that a try.
Regards.