【发布时间】:2019-02-16 21:01:47
【问题描述】:
加粗是我试图让程序在输出时忽略纯文本中的空格。我对如何做到这一点感到困惑。当我运行程序时,它不会忽略空格。相反,它的运行就像加粗的 else if 语句不存在一样。我很困惑为什么会这样。如果我的代码有点乱,我很抱歉。我刚开始编程。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int shift(char c);
int main(int argc, string argv[])
{
// Check to see if two arguments are enterted at launch
int cipher = 0;
if (argc != 2)
{
// If not return error & return 0
printf("Usage: ./vigenere keyword \n");
return 1;
}
else
{
int strlength = strlen(argv[1]);
// Iterates through characters in second argument (key), checking to see
// if they are digits
for (int k = 0; k < strlength; k++)
{
if (!isalpha(argv[1][k]))
{
// If not return error & return 1
printf("Usage: ./vigenere keyword\n");
return 2;
}
}
//char *c =argv[1];
string plaintext = get_string("Plaintext: ");
int len = (int)strlen(plaintext);
//int b = atoi(c);
char code[len];
strcpy(code, plaintext);
for (int j = 0; j < len; j++)
{
int key = shift(argv[1][j]);
if (isupper(argv[1][0]))
{
cipher = ((((code[j] - 'A') + key) % 26) + 'A');
//printf("%c", (((plaintext[j] - 'A') + key) % 26) + 'A');
//printf("%c",cipher);
}
else if (islower(argv[1][0]))
{
cipher = ((((code[j] - 'a') + key) % 26) + 'a');
//printf("%c", (((plaintext[j] - 'a') + key) % 26) + 'a');
printf("%c",cipher);
}
else if (!isalpha(code[j]))
{
code[j] = 0;
}
/* else
{
printf("%c", code[j] + (cipher));
}
*/
}
printf("\n");
}
}
int shift(char c)
{
int i = c;
if (i <= 'Z' && i >= 'A')
{
return ((i - 'A') % 26);
}
else
{
return ((i - 'a') % 26);
}
}
【问题讨论】:
-
为什么不用
if (!isalpha(argv[1][k]))而不是if (isdigit(argv[1][k]))? (除非您允许标点符号)char code[len];必须是char code[len+1];(对于 nul-terminating 字符)。你不需要else if (!isalpha(code[j])),只需要else,如果不是upper而不是lower,就不是alpha。 -
谢谢!我做了那个改变。
-
另外,您担心打印的空间是多少?对于任何字符串,您可以使用
for (int i = 0; mystring[i]; i++) { if (!isspace (mystring[i]) putchar (mystring[i]); } putchar ('\n');打印每个非空格字符 -
我在输入纯文本时担心空格。
-
哦,有道理,那么你可以这样做,例如
string newst = get_string ("input: "); char strnospc[strlen(newst)+1]; size_t ndx=0; for (int i = 0; newst[i]; i++) { if (!isspace (newstr[i])) strnospc[ndx++] = newstr[i]; } newstr[ndx] = 0;现在strnospc包含newstr中内容的nul-terminated 副本,没有任何空格。ndx现在拥有长度strnospc(与strlen (strnospc)相同)您可以在没有get_string的情况下执行相同的操作,只需使用getchar()读取具有相同测试的输入即可。 (由你决定)
标签: c encryption cs50 vigenere