c_cpp 第1周续:Vigen3 - 更复杂的输入字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 第1周续:Vigen3 - 更复杂的输入字符串相关的知识,希望对你有一定的参考价值。

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

bool check_alpha(string k);

// this code is for if the plain text has more than one string with space in between

int main(int argc, string argv[])
{
	if (argc != 1)
	{
		// get key from command line argument
			string key = argv[(argc - 1)];
			int l_key = strlen(key);

		// check if the key string is alphabetical
			bool y = check_alpha(key);

			if ( y )
			{
					// prompt for plaintext
						string text = get_string("Please type your text: ");
						int l_text = strlen(text);



					// for each character in the plaintext string
						if (l_text!= 0)
						{
							// set counter for key string and plain text string
								int i = 0;
								int index_k =0;

								while (text[i] != '\0')
								{
									// if alphabetic
										if (isalpha(text[i]))
										{
											// preserve case
												if(isupper(text[i]))
												{
												// shift plaintext character by according char in key string
													// convert the according char in key string to alphabetical index
														int k = key[(index_k%l_key)] - 'a';

													// convert the according char in plain text string to alphabetical index
														int p = text[i] - 'A';

													// convert to ciphertext letter: c = (p+k)%26
														int c = (p+k)%26;

													// convert to ascii for upper case char
														text[i] = c + 'A';
												}

												else
												{
												// shift plaintext character by according char in key string
													// convert the according char in key string to alphabetical index
														int k = key[(index_k%l_key)] - 'a';

													// convert the according char in plain text string to alphabetical index
														int p = text[i] - 'a';

													// convert to ciphertext letter: c = (p+k)%26
														int c = (p+k)%26;

													// convert to ascii for upper case char
														text[i] = c + 'a';
												}

												i++;
												index_k++;

										}

										else
										{
											i++;
										}
								}

							// print ciphertext
								printf("The crypto-text is: %s\n", text);
						}
			}
			else
			{
				printf("The key string is not alphabetical.\n");
			}

	}
}

bool check_alpha(string k)
{
	int l=strlen(k);
	int i=0;
	while ( (k[i] != '\0') && (isalpha(k[i])) )
	{
		i++;
	}
	if ( i == l )
	{
		return true;
	}
	else
	{
		return false;
	}
}

以上是关于c_cpp 第1周续:Vigen3 - 更复杂的输入字符串的主要内容,如果未能解决你的问题,请参考以下文章

c_cpp 第1周续:Vigen2 - 输入文本没有空格,只有1个长字符串

text 第1周续:解释Vigen的3个代码

第二周续.(代码)

c_cpp 复杂的模板类

c_cpp 复杂的类

c_cpp 复杂