【问题标题】:Casting a character into an int which is located within a string within argv[1]将字符转换为位于 argv[1] 内的字符串中的 int
【发布时间】:2015-07-24 02:45:00
【问题描述】:

我试图在存储在argv[1] 中的字符串和一个名为k 的int 变量中转换一个字符,该变量将具有相应的ASCII 值。

此外,我正在投射的这个字符也将通过另一个名为 c 的 int 变量控制的 for 循环不断变化。我在下面发布代码。

让我知道我做错了什么,因为我不断收到许多不同的错误消息。

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

int main(int argc, string argv[])
{
int a = argc;
if (a != 2)
{
    return 1;
}

string b = argv[1];
//b IS THE CODE WORD
string ptext;
//ptext IS THE MESSAGE TO BE ENCRYPTED

if (isalpha(b))
{
    ptext = GetString();
}
else
return 1;

//this is to index the letters within the code word       
for (int c = 0, d = strlen(b); c < d; c++)      
{ 
int k = (b(char[c]));     
    //this is to index the letters within the plaintext         
    for (int i = 0, l = strlen(ptext); i < l ;i++)
    {
        while (isalpha(ptext[i]))
        {
        printf("%c", b[c]%d+k);
        }              
    }    
  }           
}

有问题的部分是从底部算起的 11 行。

【问题讨论】:

  • 什么错误信息?
  • 还有,string是什么?
  • 字符串是一个字符数组。 GetString 是 库中的一个函数,很抱歉没有将它包含在代码中。我收到的错误消息各不相同。对于现在的代码,错误消息是“预期表达式”,带有一个指向字符 c 的小指针
  • @OliverCharlesworth 显然这个“cs50”的东西包括 typedef char *string; 。不混淆,一点也不...
  • int k = (b(char[c])); 应该读作int k = b[c] - '0';,但稍后b[c]%d+k 是不正确的,你需要重新考虑那个。另外,isalpha(b) 是非法的,你应该得到关于它的编译器消息。

标签: c cs50


【解决方案1】:

我已尝试根据我的 Linux 系统修改您的代码,并根据您提供(或者更确切地说未提供)的数据,在代码中到处进行少量修改。

我希望这可以帮助您了解代码中的问题。

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

#define string char*
int main(int argc, string argv[])
{
int a = argc;
if (a != 2)
{
    return 1;
}

string b = argv[1];
//b IS THE CODE WORD
string ptext;
//ptext IS THE MESSAGE TO BE ENCRYPTED

if (isalpha(b))
{
    //ptext = GetString();
    ptext = "Hello World";
}
else
return 1;

//this is to index the letters within the code word
int c = 0;
int d;
for (c = 0, d = strlen(b); c < d; c++)
{
//int k = (b(char[c]));
int k = *(b+c);
    //this is to index the letters within the plaintext
    int i = 0;
    int l;
    for (i = 0, l = strlen(ptext); i < l ;i++)
    {
        //This will cause buffer overflow, so commenting
        /*
        while (isalpha(ptext[i]))
        {
        printf("%c", b[c]%d+k);  //what are you trying to print as %d here
        }
        */
    }
}
}

【讨论】:

  • #define string char* 请不要...这是typedef 的用途。
猜你喜欢
  • 1970-01-01
  • 2013-03-02
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 2011-10-02
  • 2011-03-06
  • 1970-01-01
相关资源
最近更新 更多