C - 字符串中的更改字母

时间:2012-10-05 14:37:19

标签: c string replace character

我有以下用C编写的应用程序:

应用程序基本上向用户显示包含一个不正确字母的单词。要求用户提供错误字母的位置并将其替换为新的字母。

问题在于,如果我尝试更改字母编号4(数组索引3),则新单词将是Act而不是Actally。如果我以编程方式执行此操作,即更改此行

string[letter_number - 1] = change;

到这个

string[letter_number - 1] = 'u'
一切正常。我该如何解决这个问题?感谢。

3 个答案:

答案 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编译器中测试了你的代码。我需要更改以下内容才能使其正常工作

  • &#34; scanf_s&#34;中的换行符;不应该在那里。其原因如下。 如果格式说明符中存在空格字符(包括空格,换行符和制表符),则scanf函数将读取并忽略(从stdin)在下一个非空白字符之前遇到的任何空格字符< / em> 。因此,在这个特定的用例中;即使在输入输入后输入密钥,您的程序执行也会在此scanf语句中等待无限
  
    

scanf_s(&#34;%c \ n&#34;,&amp; change); //将其更改为

         

scanf(&#34;%c&#34;,&amp; change);

  
  • 按照我的说法,使用&#34; getchar&#34;在scanfs之后。最合适的方法应该是在第一次scanf之后刷新输入缓冲区,这样第二次scanf实际上需要用户输入而不是从输入缓冲区中选择。

PS:请注意fflush(stdin)不适用于GCC。