0

再一次,我发现自己相对迷失,并从同龄人那里寻求知识。我需要做的是编写一个程序,该程序采用编码语言,在辅音后添加字母“u”“t”并输出为英文。因此输入的 Hutelutluto 将输出为 hello。起初我以为我已经弄清楚了,但后来我的教授说我必须将初始输入存储在字符数组中并显示它。然后使用该字符数组输出修改后的翻译。

我尝试了几种不同的角度,一种尝试修改我的 readstring 函数以适应我的修改参数。它总是最终变得一团糟并给我意想不到的输出。

本质上,我相信我需要帮助将字符数组输入 while 循环,但是当我尝试时,我得到一个错误,指出我有一个与整数错误的指针比较。

这是我的代码版本,我相信我最接近解决问题。目前 while 独立于 readstring 函数工作。我确定我想多了这个问题,但我只是不知道如何解决这些问题。:

/*

Tut language
By: Steven

*/

# include <stdio.h>
void readstring(char *, int);

int main (void){
  char input [50];
  char output;
  char trash;

//initiation
printf("\n\t*Hi! Welcome to the assemble of Tut*\n");
printf("I can help you decode/encode a message to and from the code called Tut!\n");
printf("Enter a sentence to be translated frome Tut - English: ");
readstring(input, 50);
printf("Your Tut sencence is: %s \n",input);








  while (output != '\n') {
    output = getchar();
    if(output == '\n'){//escape sequence
      break;
    }
      if((output != 'a') && (output != 'e') && (output != 'i') && (output != 'o') && (output != 'u') && (output != 'y') && (output != ' ')){
        putchar(output);
        trash = getchar();
        trash = getchar();
      }else{
        putchar(output);
      }
  }
  return 0;
}// end main

//function lists start
void readstring(char * buffer, int size) {
  int x;
  char c = getchar( );

  if( c == '\n' ) {
    c = getchar( );
  }

  for(x = 0 ; (x < (size-1)) && c != '\n' ; x++) {
    buffer[x] = c;
    c = getchar( );
  }

  buffer[x] = '\0';
}

任何帮助或反馈将不胜感激!感谢您的宝贵时间!

ps

在考虑了您的建议后,我编辑了我的代码,但似乎它忽略了第一个之后的所有输入。我什至尝试将 !='\n' 条件更改为 i < 50,但我得到了相同的结果。

采纳 Tim 的建议后的代码行:

    for (i = 0; input [i] != '\n'; ++i){
    output = input[i];
      if((output != 'a') && (output != 'e') && (output != 'i') && (output != 'o') && (output != 'u') && (output != 'y') && (output != ' ')){
        putchar(output);
        trash = getchar();
        trash = getchar();
      }else{
        putchar(output);
      }
  }
4

3 回答 3

0

主要问题出在您的 while 循环中。在这个循环中,您使用的是 getchar,它试图从标准输入中读取。但是,您已经读取了输入,并且它存储在缓冲区中。

因此,您应该从缓冲区中获取字符,而不是再次读取它们。

于 2015-12-07T21:24:27.950 回答
0

您的readstring函数已经调用getchar从用户终端读取字符,因此您不需要在readstring完成后再次调用它。相反,使用for循环output依次设置输入字符串的每个字符:

int i;
for i = 0; input[i] != '\n'; ++i {
    output = input[i]
    if((output != 'a') && (output != 'e') && (output != 'i') && (output != 'o') && (output != 'u') && (output != 'y') && (output != ' ')){
        ...
于 2015-12-07T21:25:46.913 回答
0

…在字符数组中,我不知道如何跳过接下来的两个字符?

通过增加数组索引来跳过字符。改变

        trash = getchar();
        trash = getchar();

        input[++i] && input[++i] || --i;    // step back if at end of string

此外,由于输入字符串由\0而不是终止\n,更改

    for (i = 0; input [i] != '\n'; ++i){

    for (i = 0; input[i]; ++i)
    {
于 2017-09-04T06:15:06.307 回答