我有以下用C编写的应用程序:
应用程序基本上向用户显示包含一个不正确字母的单词。要求用户提供错误字母的位置并将其替换为新的字母。
问题在于,如果我尝试更改字母编号4(数组索引3),则新单词将是Act而不是Actally。如果我以编程方式执行此操作,即更改此行
string[letter_number - 1] = change;
到这个
string[letter_number - 1] = 'u'
一切正常。我该如何解决这个问题?感谢。
答案 0 :(得分:1)
用简单的scanf_s
替换您的scanf
即可完成。否则你可以使用
scanf_s("%d ", ...);
并删除getchar();
这对我有用:
#include <string.h>
#include <stdio.h>
int main()
{
char string[9] = "Actwally";
int letter_number;
char change;
printf("---Spot the Odd Letter Out---\n\n");
printf("The word below contains one letter which is incorrect:\n\n");
printf("Word: %s\n\n\n", string);
printf("Please provide the position of the incorrect letter and propose a new letter\n\n");
printf("Position of incorrect letter: ");
scanf("%d ", &letter_number);
printf("\nProposed new letter: ");
scanf("%c ", &change);
string[letter_number - 1] = change;
printf("\n\nThe new word looks like this %s\n\n\n", string);
if(strcmp("Actually", string) == 0)
{
printf("You are right! Congratulations!");
}
else
{
printf("Sorry, but you have not guessed the word. Better luck next time!");
}
printf("\n\n\nPlease press enter to exit the program");
getchar();
}
答案 1 :(得分:0)
使用前确认输入正确无误。听起来好像change
被设置为0,终止了字符串。
我不确定getchar()
来电之间的scanf()
来电,他们可能会失去输入。
答案 2 :(得分:0)
马修,
基本上我在GCC编译器中测试了你的代码。我需要更改以下内容才能使其正常工作
scanf_s(&#34;%c \ n&#34;,&amp; change); //将其更改为
scanf(&#34;%c&#34;,&amp; change);
PS:请注意fflush(stdin)不适用于GCC。