|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<stdio.h>
- int main()
- {
- char str1[100],str2[100];
- printf("Please input the first string:");
- scanf("%s",&str1);
- printf("Please input the second string:");
- scanf("%s",&str2);
-
- signed int i;
-
- printf("Please input the number you'd like to compare:");
- scanf("%d",&i);
-
- if (str1[i]==str2[i])
- {
- printf("The result is 0!\n");
- }
- else
- {
- printf("The result is %d\n",str1[i]-str2[i]);
- }
- return 0;
- }
复制代码
如果输入的字符串中间有空格就出错,为什么?
本帖最后由 一点点儿 于 2022-8-9 15:44 编辑
scanf扫描到空格时,就认为对str的赋值结束,并忽略了后面的字符串。注意:后面的字符串依然还在stdin缓冲区。
怎么才能解决这样的问题呢?
可以用gets()代替scanf():scanf("%s",&str1)改为gets(str1)
scanf("%s",&str2)改为gets(str2)
如下:
- #include <stdio.h>
- int main() {
- char str1[100], str2[100];
- printf("Please input the first string:");
- gets(str1);
- printf("Please input the second string:");
- gets(str2);
- signed int i;
- printf("Please input the number you'd like to compare:");
- scanf("%d", &i);
- if (str1[i] == str2[i]) {
- printf("The result is 0!\n");
- } else {
- printf("The result is %d\n", str1[i] - str2[i]);
- }
- return 0;
- }
复制代码
|
|