C 的字符和字符串

Characters and Strings with C

我正在开发用 C 编写的 restful 客户端。这很简单,我只需要通过 post 发送一个人名(John、Sam、Muhammad 等等... ) 我在终端上写的。

我的整个代码工作正常,但我在转换字符或字符串方面遇到一些问题,由 post 发送。

我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>

int main(void) {

CURL *curl;
CURLcode res;

int x = 1;
unsigned char m;

while (x != 0) {
    printf("Opcao 1 para incluir nova pessoa\n");
    printf("Opcao 2 para listar pessoas\n");
    printf("Opcao 0 para sair\n");
    printf("Selecione a opcao: ");
    scanf("%d",&x);

    if (x == 1) {
        printf("Nome da pessoa: ");
        scanf("%s",&m);

        curl = curl_easy_init();
        if(curl) {
            curl_easy_setopt(curl, CURLOPT_URL, "localhost/wsRest/index.php/novo/" );
            curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "");
            res = curl_easy_perform(curl);
            if(res != CURLE_OK)
                fprintf(stderr, "curl_easy_perform() failed: %s\n",
                  curl_easy_strerror(res));
            curl_easy_cleanup(curl);
        }
    }

    printf("\n");
}

curl_global_cleanup();
return 0;

}

我需要找到一种方法将写在变量 'm' 上的名称放在 curl_easy_setopt() 函数中,与我的 URL 连接起来,但我不知道该怎么做它,以及我发现的示例甚至无法将 URL 读取到另一个变量...

我该怎么做?

谢谢大家!

这不会像您期望的那样工作:

scanf("%s", &m);

m 是一个 unsigned char,scanf %s 修饰符将尝试读取一个字符串,将其写入您提供给它的指针,然后以 null 终止它。对于任何非空名称,它将写入无效内存(如果幸运的话,这应该会崩溃)。

确实,您传递了一个指向字符的指针,但是只有 space 表示 1 个字符。

您应该改用数组,例如:

char m[512];
/* ... */
scanf("%s", m);

请注意,这为名称长度设置了 511 的上限。如果您希望名称更长,请增加缓冲区大小。

更新:

您可以通过以下方式在 URL 前面添加:

char m[512];
int idx = sprintf(m, "localhost/wsRest/index.php/novo/");
/* ... */
scanf("%s", &m[idx]);

然后将 m 作为 url 传递。

首先将 URL 路径存储在 m 中,然后将输入字符串读入缓冲区的其余部分。 sprintf(3) returns写入的字符数,所以idx是URL路径后第一个位置的偏移量。

如果要附加,则 scanf("%s", m) 然后使用 strcat(m, "localhost/wsRest/index.php/novo/")

同样,这假定名称 + URL 大小小于 511。

首先,您需要一个数组来保存用户输入的名称。改变这个

unsigned char m;

至此

char m[1000];

接下来,您需要一个数组来保存 URL

char url[1200];

然后您可以使用sprintf将名称附加到URL

sprintf( url, "localhost/wsRest/index.php/novo/%s", m ); 

最后将 url 传递给 setopt 函数

curl_easy_setopt(curl, CURLOPT_URL, url);