在按字符串按' - &#x27中的字符串中找到每个字符的ASCII。
所以,我想用c编写一个程序,在其中输入一个字符串,然后输出将是该字符串中每个字符的ascii编号,并用“-”分隔。我几乎完成了,然后我不知道如何删除代码输出中的最后一个“-”。实验值。输入:abc 输出:97-98-99。 这是我的代码:
char s[1001];
scanf("%s",&s);
for(int i=0;s[i]!='\0';i++){
printf("%d-",s[i]);
}
return 0;
}
我的输出:97-98-99-
So, i want to make a program in c where you input a string then the output will be ascii number of every character in that string split by '-'. i almost done then i dont know how to remove the last '-' in the output of my code. exp. input: abc output: 97-98-99.
Here is my code :
char s[1001];
scanf("%s",&s);
for(int i=0;s[i]!='\0';i++){
printf("%d-",s[i]);
}
return 0;
}
My output : 97-98-99-
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
检查当前索引是否不是最后一个索引,然后打印
-
,否则它是最后一个索引并打印换行
check if current index is not the last index then print
-
otherwise it's the last index and printnewline
无需在循环中使用
strlen()
、length 或重复测试,只需更改分隔符即可。Instead of using
strlen()
, length or repeated tests in a loop, simply change the separator.我们将使用三元运算符来检查
i<通过检查
s[i + 1] != 0
,/code>是'\0'
之前的最后一个字符,这里i
是当前字符串的索引。这是一个视觉表示。注意:您的变量
char s[1001]
将衰减为指针(例外:sizeof
运算符)。一些改进:
"%s"
,使用"%s"
,以避免缓冲区溢出size_t
迭代数组。return 0;
,而是使用return EXIT_SUCCESS;
,它是在头文件stdlib.h
中定义的。scanf()
输入是否成功最终代码:
输出:
We'll use Ternary Operator, to check whether
i
is the last character before'\0'
by checkings[i + 1] != 0
, herei
is the current index of the string. Here's a visual representation.NOTE: Your variable
char s[1001]
will be decayed to a pointer (exception:sizeof
operator).Some improvements:
"%s"
, use"%<WIDTH>s"
, to avoid buffer-overflowsize_t
to iterate through an array.return 0;
, usereturn EXIT_SUCCESS;
, which is defined in the header filestdlib.h
.scanf()
input was successful or notFinal Code:
Output:
稍微重新排列您的逻辑:
Slightly rearrange your logic: