Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何获取输入以提示用户输入两个字符并使用它们进行交换?_C_Sorting_Loops_Pointers - Fatal编程技术网

C 如何获取输入以提示用户输入两个字符并使用它们进行交换?

C 如何获取输入以提示用户输入两个字符并使用它们进行交换?,c,sorting,loops,pointers,C,Sorting,Loops,Pointers,我正在使用Ubuntu中的GCC用ANSIC制作一个小应用程序。应用程序应该通过交换数组中的两个字母来破译消息 我的主要班级: #include "CipherCode.h" char cipherText[] = "PUCXHTULUL, XW AELW, JUAJ TXJ FOCTXWU EH XW OCCQLPOWCU RXAT ATU DUZ GXJA. RTUW ATU FUJJOBU XJ LUCUXIUP, TU JUAJ ATU DUZ RTUUGJ AQ ATU"; int

我正在使用Ubuntu中的GCC用ANSIC制作一个小应用程序。应用程序应该通过交换数组中的两个字母来破译消息

我的主要班级:

#include "CipherCode.h"

char cipherText[] = "PUCXHTULUL, XW AELW, JUAJ TXJ FOCTXWU EH XW OCCQLPOWCU RXAT ATU DUZ GXJA. RTUW ATU FUJJOBU XJ LUCUXIUP, TU JUAJ ATU DUZ RTUUGJ AQ ATU";

int main(void) {
    char ch = 0;
    char chLetter, chReplacement;

    char *pLetter = chLetter;
    char *pReplacement = chReplacement;

    int cipherStats[ALPHABET_SIZE] = { 0 };
    char chAlphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    int *pCipherStats = cipherStats; 
    char *pCipherText = cipherText;
    char *pAlphabet = chAlphabet;

    do {
        DisplayCipherText(pCipherText);
        GetFrequency(pCipherText, pCipherStats);
        DisplayCipherStats(pCipherStats, pAlphabet, 26);
        chLetter = GetLetter("Enter character to substitute:");
        chReplacement = GetLetter("Swap this with character:");
        Decipher(pCipherText, pReplacement);
        printf("%s", "\nPress 'n' to exit or any other key to continue...\n"); /* prompt to continue looping */
    } while ((ch = getchar()) != 'n'); /* loop unless user enters char 'n' */

    return EXIT_SUCCESS;
}
我的CipherCode.c文件:

#include "CipherCode.h"

char GetLetter(const char* prompt) {
    char ch = '\0';
    do {
        printf( "%s", prompt ); 
        fflush(stdout);
        ch = toupper(getchar());
        printf( "%c\n", ch );
    } while (!isalpha(ch));
    return ch;
}

int GetFrequency(const char *pCipherText, int *pCipherStats) {
    printf("Frequency analysis:\n");
    for (; *pCipherText != '\0'; pCipherText++) {
        if (isalpha(*pCipherText)) {
            int index = toupper(*pCipherText) - 'A';
            if ( index >= 0 && index < 26 ) {
                pCipherStats[index]++;
            }
            else {
                fprintf(stderr, "%c gives invalid index: %d\n", *pCipherText, index);
            }
        }
    }
    return EXIT_SUCCESS;
}

void DisplayCipherText(char *pCipherText) {
    for (; *pCipherText != '\0'; pCipherText++) {
        printf("%c", *pCipherText);
    }
    printf("\n\n");
}

void DisplayCipherStats(int *pCipherStats, char *pAlphabet, int size) {
    int i;
    for (i = 0; i < size; i++) { /*for each letter in the alphabet*/
        printf("%1c:%-4d", *pAlphabet++, *pCipherStats++); /*print frequency information*/
    }
    printf("\n\n");
}

void Decipher(char *pCipherText, char *pReplacement) {
    for (; *pCipherText != '\0'; pCipherText++) {
        if (*pCipherText == *pReplacement) {
            SortChar(pCipherText, pReplacement);
        }
    }
}

void BubbleSort(int *pInt, char *pCh) {
    int i, j;
    for (i = ALPHABET_SIZE-1; i >= 0; i--) {
        for (j = 0; j < i; j++) {
            if (*(pInt+j) < *(pInt+j+1)) {
                SortChar(pCh+j, pCh+j+1);
                SortInt(pInt+j, pInt+j+1);
            }
        }
    }
}

void SortInt(int *pIntA, int *pIntB) {
    int tempInt; /*temp variable*/
    tempInt = *pIntA; /*store old value before it is overwritten*/
    *pIntA = *pIntB; /*overwrite old value*/
    *pIntB = tempInt; /*complete the swap*/
}

void SortChar(char *pChA, char *pChB) {
    char tempCh; /*temp variable*/
    tempCh = *pChA; /*store old value before it is overwritten*/
    *pChA = *pChB; /*overwrite old value*/
    *pChB = tempCh; /*complete the swap*/
}
#包括“CipherCode.h”
char GetLetter(const char*prompt){
char ch='\0';
做{
printf(“%s”,提示符);
fflush(stdout);
ch=toupper(getchar());
printf(“%c\n”,ch);
}而(!isalpha(ch));
返回ch;
}
int GetFrequency(常量字符*pCipherText,int*pCipherStats){
printf(“频率分析:\n”);
对于(;*pCipherText!='\0';pCipherText++){
if(isalpha(*pCipherText)){
int index=toupper(*pCipherText)-“A”;
如果(索引>=0&&index<26){
pCipherStats[索引]+;
}
否则{
fprintf(stderr,“%c给出的索引无效:%d\n”,*pCipherText,索引);
}
}
}
返回退出成功;
}
无效显示密文(char*pCipherText){
对于(;*pCipherText!='\0';pCipherText++){
printf(“%c”,*pCipherText);
}
printf(“\n\n”);
}
void display密码状态(int*pCipherStats,char*pAlphabet,int size){
int i;
对于字母表中的每个字母(i=0;i=0;i--){
对于(j=0;j
我的头文件:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define ALPHABET_SIZE 26

/*
* global variables
*/
extern char cipherText[];

/*
* function prototypes
*/
char GetLetter(const char*);
int GetFrequency(const char*, int*);
void DisplayCipherText(char*);
void DisplayCipherStats(int*, char*, int);
void Decipher(char*, char*);
void BubbleSort(int*, char*);
void SortInt(int*, int*);
void SortChar(char*, char*);
#包括
#包括
#包括
#定义字母表大小26
/*
*全局变量
*/
外部字符密文[];
/*
*功能原型
*/
char GetLetter(const char*);
int GetFrequency(常量字符*,int*);
无效显示密文(字符*);
无效显示密码状态(int*,char*,int);
无效解密(字符*,字符*);
void BubbleSort(int*,char*);
无效排序(int*,int*);
void SortChar(char*,char*);
我希望该计划采取chLetter和取代所有出现的chLetter在密文与chReplacement。对于do循环的每次迭代,我想显示密文,然后分析密文中字母的频率,然后显示频率,然后询问chLetter,然后询问chReplacement,最后用chReplacement交换chLetter

程序必须使用指针来引用数组的内容。我还必须使用排序函数来破译文本

非常感谢您的帮助。谢谢。

GetLetter()
GetReplacement()
有多个问题

第一行将其定义为一个函数,它接受
char
并返回
char
。 这实际上是可以的,但是因为在中不使用传递的值
chLetter
,您根本不需要传递它

char GetLetter(char chLetter) {
这条线并不像你想象的那样。它不会使用文本
“输入字符…”
作为提示,但请尝试将输入与之匹配。这 意味着
scanf
不会失败的唯一方法是用户键入 整个字符串,这显然不是你想要的。
scanf
也不会返回
char*
,而是返回一个
int
,指示有多少个字符 输入项已成功匹配或
EOF
,如果输入结束 在匹配第一项之前已到达或发生错误。分配
int
指针的值通常是无意义的

char *pLetter = scanf("Enter character to substitute: %c", &chLetter);
在这里,您试图取消引用一个不指向有效对象的指针 内存位置

return *pLetter;
}
一个简单的实现可以是:

/** Prompt for inputting a single character
 *
 * Reads the first character and then discards the rest of the line.
 * The `text` parameter is the prompt string.
 * Returns an int so we can indicate EOF, which isn't representable by char
 */
int prompt_char(const char *text) {
    int c, tmp;
    printf("%s: ", text);
    c = getchar();
    do {
        tmp = getchar();
    } while (tmp != '\n' && tmp != EOF);
    return c;
}
您可以从
main()
中使用它,如下所示:

do {
    ...
    chLetter = prompt_char("Enter character to substitute");
    chReplacement = prompt_char("Swap this with character");
            if (chLetter == EOF || chReplacement == EOF) {
                // do something, e.g. break from the loop or exit the program
            }
    ...
} while (...)
char GetLetter() 
{
  printf( "%s", "Enter character to substitute:"); 
  fflush(stdout);
  return getchar();
}
^指定scanf格式字符串的方式错误,格式字符串用于 匹配缓冲区中的输入,而不是显示提示。scanf返回数字 从缓冲区中找到的参数的个数,而不是字符*

相反,你可以这样做:

do {
    ...
    chLetter = prompt_char("Enter character to substitute");
    chReplacement = prompt_char("Swap this with character");
            if (chLetter == EOF || chReplacement == EOF) {
                // do something, e.g. break from the loop or exit the program
            }
    ...
} while (...)
char GetLetter() 
{
  printf( "%s", "Enter character to substitute:"); 
  fflush(stdout);
  return getchar();
}
或者,为了使其更灵活,请在参数中指定提示:

char GetLetter(const char* prompt) 
{
  printf( "%s", prompt ); 
  fflush(stdout);
  return getchar();
}
那你就可以用

char chReplace = GetLetter("Enter character to substitute:");
char chWith = GetLetter("Swap this with character:");
具有此功能

int GetFrequency(char *pCipherText, int *pCipherStats) {
printf("Frequency analysis:\n");
for (; *pCipherText != '\0'; pCipherText++) { /*check if at the end of the array*/
    char ch = *pCipherText; /*store current letter as a char*/
    if (isalpha(ch)) pCipherStats[ch - 'A']++; /*if character is a letter, store ascii value in array and increment array*/
}
^您似乎假设所有输入字母都是大写的,也许您应该首先将字符转换为大写来确保这一点。编程时,最好是安全而不是遗憾。通常,通过将参数用作临时变量来修改参数不是一种好的方式,当函数更复杂时,可能会使代码混乱。而是使用本地变量,例如

int GetFrequency(const char *pCipherText, int *pCipherStats) 
{
  char* p = pCiperText;
  printf("Frequency analysis:\n");
  for (; *p != '\0'; ++p) 
  {
    if (isalpha(*p)) 
    {
      int index = toupper(*p) - 'A';
      if ( index >= 0 && index < 26 )
      {
        pCipherStats[index]++;
      }
      else
      {
        fprintf(stderr, "%c gives invalid index: %d\n", *p, index );
      }
    }
  }
  ...

char chAlphabet[ALPHABET_SIZE]={'A','B','C','D','E',…
很难看,你可以用一个小循环来生成它。没错!
char chAlphabet[ALPHABET_SIZE];
for(i=0;ior只是
char chAlphabet[]=“abcdefghjjjklmnopqrstuvxyz”
,多余的\0不会造成太大伤害,甚至可能有帮助…
scanf
不会返回
char*
@rmartinjak,而是
char chalpabet[26]=“ABCD…”
对于完全相同的结果,没有第26个元素为零,但这看起来与OP已经拥有的没有太大区别……这是如何获得任何输入的?我想