【问题标题】:Combining user input with a string literal in C将用户输入与 C 中的字符串文字相结合
【发布时间】:2021-07-27 06:52:59
【问题描述】:

我正在尝试将字符串文字与来自用户的输入结合起来,并将其作为一条消息存储在一个数组中。然后我必须将该消息发送到服务器。我还很新,对指针仍然有些困惑。 这是我迄今为止尝试过的:

char input[1000];
char filename[100];
char message[2000];
printf("Please enter the name of a file \n");
scanf("%s", filename);
printf("what would you like to write to the file ?\n");
scanf("%s",input);
message = ("Write to file %s the following input: \n", filename, input);
if (send(csocket , message , strlen(message), 0) < 0)
{
  printf("send failed \n");
}

【问题讨论】:

标签: arrays c string sockets pointers


【解决方案1】:

鉴于"Write to file %s …" 的性质,您可能需要使用snprintf()(在其他情况下,您可能需要使用strcpy()strcat() — 至少,这些是最简单的工具,即使不是完全安全)。 C 没有内置的字符串操作;你必须使用函数来处理字符串。

char input[1000];
char filename[100];
char message[2000];

printf("Please enter the name of a file \n");
if (scanf("%s", filename) != 1)
    …process error…
printf("what would you like to write to the file ?\n");
if (scanf("%s", input) != 10
    …process error…
snprintf(message, sizeof(message), "Write to file %s the following input: %s\n",
         filename, input);
if (send(csocket, message, strlen(message), 0) < 0)
{
    fprintf(stderr, "send failed\n");
}

注意:scanf("%s", …) 只读取一个“单词”——它会跳过前导空白字符(空格、制表符、换行符),然后读取一系列非空白字符直到下一个空白字符。而且您没有限制输入的长度;你应该! (那就是scanf("%99s", filename)scanf("%999s", input) — 长度上的一对一是可悲的,但历史悠久,因此实际上是不可改变的。)

【讨论】:

  • 谢谢你这完全解决了我的问题,我也非常感谢你留下的笔记
猜你喜欢
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多