【问题标题】:C - Change Letter in StringC - 更改字符串中的字母
【发布时间】:2012-10-05 14:37:19
【问题描述】:

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

该应用程序基本上会向用户显示一个包含一个错误字母的单词。请用户提供错误字母的位置并用新字母替换。

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

string[letter_number - 1] = change;

到这里

string[letter_number - 1] = 'u'

一切正常。请问我该如何解决这个问题?谢谢。

【问题讨论】:

  • 您正在丢弃scanf 的返回值。这是一个严重的编程错误,在您修复此问题之前几乎没有必要猜测。

标签: c string replace character


【解决方案1】:

用简单的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();
}

【讨论】:

  • 谢谢。现在我终于可以删除 getchar() 了。但我的问题仍然存在:(
  • 非常感谢。您的回答帮助我解决了问题:)
【解决方案2】:

在使用之前验证您的输入是否正确。听起来好像change 被设置为 0,终止字符串。

我不确定您在scanf() 调用之间的getchar() 调用,它们可能会丢失输入。

【讨论】:

  • 如果没有 getchar(),出于某种原因,程序不允许我提供第二个输入(新字母)。有办法解决吗?我是 C 的新手。此外,我正在 Visual Studio 中编程。这会产生任何问题吗?
  • 我不认为 getchar 有效果,因为程序在正确的位置更改字符串,所以 letter_number 中的值不会丢失。问题在于变化的价值。
  • @Matthew,丢掉 get_char 并将 scanf" %c"(% 前有空格)一起写入以跳过空格。
  • 或者用“%d”写上一个,但无论如何替换scanf_s
【解决方案3】:

马修,

基本上我在 GCC 编译器中测试了你的代码。我需要更改以下内容以使其正常工作

  • “scanf_s”中的换行符不应存在。其原因如下。 如果格式说明符中存在空白字符(包括空格、换行符和制表符),scanf 函数将读取并忽略(从标准输入)在下一个非空白字符之前遇到的任何空白字符 。因此,在这个特定的用例中;您的程序执行将在此 scanf 语句中无限地等待,即使您输入了输入并按回车键。

scanf_s("%c\n", &change); //如下修改

scanf("%c", &change);

  • 在我看来,在 scanfs 之后使用“getchar”的目的较少。最合适的方法应该是在第一个 scanf 之后刷新输入缓冲区,以便第二个 scanf 实际上期望用户输入而不是从输入缓冲区中选择。

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

【讨论】:

    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多