我用C语言编写的应用程序如下:Ç - 更改代号在字符串
的应用基本上呈现包含一个不正确字母词的用户。要求用户提供不正确字母的位置并用新字母替换。
问题是,如果我尝试更改字母数字4(数组索引3),新单词将是Act而不是实际。如果我这样做编程,就是这条线
string[letter_number - 1] = change;
改变这种
string[letter_number - 1] = 'u'
一切工作正常。我该如何解决这个问题?谢谢。
我用C语言编写的应用程序如下:Ç - 更改代号在字符串
的应用基本上呈现包含一个不正确字母词的用户。要求用户提供不正确字母的位置并用新字母替换。
问题是,如果我尝试更改字母数字4(数组索引3),新单词将是Act而不是实际。如果我这样做编程,就是这条线
string[letter_number - 1] = change;
改变这种
string[letter_number - 1] = 'u'
一切工作正常。我该如何解决这个问题?谢谢。
用简单的scanf
代替scanf_s
即可完成。否则,你可以使用
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();
}
在使用它们之前请验证您的输入是否正确。这听起来好像change
设置为0,终止字符串。
我不确定您的getchar()
电话之间的电话是scanf()
,他们可能会失去输入。
马修,
基本上我在GCC编译器测试你的代码。我是在需要改变下面的东西,使之在“scanf_s”工作
scanf_s( “%C \ n” 个,&变化); //更改如下
scanf(“%c”,&变更);
PS:请注意,fflush(stdin)不会与GCC一起使用。
您放弃了'scanf'的返回值。这是一个严重的编程错误,在解决这个问题之前,一点猜测都没有。 –