我是编码(和这个网站)的新手,正在学习 cs50 课程。
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
int main(int argc, string argv[])
{
int len = strlen(argv[1]);
if(len != 26)
{
printf("Usage: ./substitution key\n");
return 1;
}
if(argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
for(int i = 0; i < len; i++)
{
if(isdigit(argv[1][i]) || ispunct(argv[1][i]))
{
printf("Usage: ./substitution key\n");
return 1;
}
for(int j = 0; j < len; j++)
{
char c = argv[1][i];
char d = argv[1][j];
int value = strcasecmp(&d, &c);
if(value != 0)
{
printf("Usage: ./substitution key\n");
return 1;
}
}
}
}
在此程序中,使用终端窗口时,字母不应重复。 例如(在终端窗口中):-
./substitution qwertyuiopasdfghjklzxcvbnp
Usage: ./substitution key
这应该是输出,但它只是绕过了此检查。 我也不知道编译程序时,它要求我在“c”和“d”之前添加“&”。如果您也解释一下这一点,我将非常感激。
strcasecmp 比较字符串,你有字符。
你需要
if (tolower(c) == tolower(d))
{
printf("Usage: ./substitution key\n");
return 1;
}
一些问题...
取消引用
if (argc != 2)
之前进行argv
检查。否则,您会遇到段错误。
tolower
与单个字符一起使用,而not
strcasecmp
则需要字符串。
i == j
时,您会得到误报。
if
重复测试的意义是相反的。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int
main(int argc, char **argv)
{
// ensure we are given an argument
if (argc != 2) {
printf("Usage: ./substitution key [no arg]\n");
return 1;
}
// point to the key string
const char *key = argv[1];
// get the key string length
int len = strlen(key);
// ensure we use all the letters
if (len != 26) {
printf("Usage: ./substitution key [bad length]\n");
return 1;
}
for (int i = 0; i < len; ++i) {
unsigned char c = key[i];
// we want _only_ letters
if (isdigit(c) || ispunct(c)) {
printf("Usage: ./substitution key [digit/punct]\n");
return 1;
}
// check for duplicate letters
for (int j = i + 1; j < len; ++j) {
unsigned char d = key[j];
if (tolower(c) == tolower(d)) {
printf("Usage: ./substitution key [duplicate '%c']\n",c);
return 1;
}
}
}
return 0;
}
char
指针而不是索引变量的版本:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int
main(int argc, char **argv)
{
if (argc != 2) {
printf("Usage: ./substitution key [no arg]\n");
return 1;
}
const char *key = argv[1];
int len = strlen(key);
if (len != 26) {
printf("Usage: ./substitution key [bad length]\n");
return 1;
}
const char *cp = key;
for (unsigned char c = *cp++; c != 0; c = *cp++) {
if (isdigit(c) || ispunct(c)) {
printf("Usage: ./substitution key [digit/punct]\n");
return 1;
}
const char *dp = cp;
for (unsigned char d = *dp++; d != 0; d = *dp++) {
if (tolower(c) == tolower(d)) {
printf("Usage: ./substitution key [duplicate '%c']\n",c);
return 1;
}
}
}
return 0;
}