繁体   English   中英

我需要在C中添加字符串字符。A+ B必须=C。

[英]I need to add string characters in C. A + B must = C. Literally

我正在编写一个应于今晚午夜的程序,我完全陷于困境。 该程序用C语言编写,并以SOS形式从用户那里获取输入,其中S =字符串,O =运算符(即IE'+','-','*','/')。 本书中的示例输入和输出如下:

输入> abc + aab

输出:abc + aab => bce

从字面上看,这不是可变的。 例如,a + a must = b。

进行此操作的代码是什么? 我将发布到目前为止的代码,但是所做的只是获取输入并将其划分到每个部分之间。

#include <stdio.h>
#include <string.h>

int main() {
  system("clear");
  char in[20], s1[10], s2[10], o[2], ans[15];

  while(1) {
    printf("\nInput> ");
    scanf("%s", in);
    if (in[0] == 'q' && in[1] == 'u' && in[2] == 'i' && in[3] == 't') {
      system("clear");
      return 0;
    }
    int i, hold, breakNum;
    for (i = 0; i < 20; i++) {
      if (in[i] == '+' || in[i] == '-' || in[i] == '/' || in[i] == '*') {
        hold = i;
      }
      if (in[i] == '\0') {
        breakNum = i;
      }
    }
    int j;
    for (j = 0; j < hold; j++) {
      s1[j] = in[j];
    }
    s1[hold] = '\0';
    o[0] = in[hold];
    o[1] = '\0';
    int k;
    int l = 0;
    for (k = (hold + 1); k < breakNum; k++) {
      s2[l] = in[k];
      l++;
    }
    s2[breakNum] = '\0';
    printf("%s %s %s =>\n", s1, o, s2);
  }
}

由于这是家庭作业,所以我们将重点放在如何解决此问题上,而不是提供一堆我怀疑您的老师会皱眉的代码。

首先,不要在main()函数中做所有事情。 将其分解为较小的功能,每个功能都完成一部分任务。

其次,将任务分解成各个组成部分并写出伪代码:

while ( 1 )
{
    // read input "abc + def"
    // convert input into tokens "abc", "+", "def"
    // evaluate tokens 1 and 3 as operands ("abc" -> 123, "def" -> 456)
    // perform the operation indicated by token 2
    // format the result as a series of characters (579 -> "egi")
}

最后,编写每个功能。 当然,如果您在途中遇到障碍,请务必再次提出您的具体问题。

根据您的示例,看起来“ a”的行为类似于1,“ b”的行为类似于2,依此类推。 鉴于此,您可以像这样对单个字符执行算术运算:

// Map character from first string to an integer.
int c1 = s1[j] - 'a' + 1;

// Map character from second string to an integer.
int c2 = s2[j] - 'a' + 1;

// Perform operation.
int result = c1 + c2;

// Map result to a character.
char c = result - 1 + 'a';

您必须添加一些内容:

  • 您必须将其循环放置,以对字符串中的每个字符进行处理。
  • 您必须根据输入中指定的运算符来更改操作。
  • 您必须对每个结果进行某些操作,可能会打印出来。
  • 您必须对超出字母范围的结果进行处理,例如“ y + y”,“ ab”或“ a / b”。

如果我们假定,从你的榜样答案,那a将是1的表示,那么你就可以找到所有的其他值的表示值和减去的值表示a从它。

 for (i = 0; i < str_len; i++) {
      int s1Int = (int)s1[i];
      int s2Int = (int)s1[i];
      int addAmount = 1 + abs((int)'a' - s2Int);
      output[i] = (char)(s1Int + addAmount)
 }

脚步

1)对于s1或s2的长度

2)检索第一个字符的十进制值

3)检索第二个字符的十进制值

4)找出字母a (97)与第二个字符+ 1 <-的差,假设a是1的表示

5)将差值添加到s1 char中,并将小数表示形式转换回一个字符。

范例1:

如果S1 char是a ,则S2 char是b

s1Int = 97

s2Int = 98

addAmount = abs((int)'a' - s2Int)) = 1 + abs(97 - 98) = 2

output = s1Int + addAmount = 97 + 2 = 99 = c

范例2:

如果S1 char为c ,则S2 char为a

s1Int = 99

s2Int = 97

addAmount = abs((int)'a' - s2Int)) = 1 + abs(97 - 97) = 1

output = s1Int + addAmount = 99 + 1 = 100 = d

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM