【问题标题】:How to return a string with variables in c如何在c中返回带有变量的字符串
【发布时间】:2017-04-05 02:40:38
【问题描述】:

我的程序正在尝试模拟自动售货机。除了退回硬币或退回零钱的部分外,一切正常。我正在尝试将插入机器的美分数量输入到主机之外的另一个代码中,然后返回一个字符串。这在 C 中是否可行,因为我不断从整数中获取初始化指针,而不会出现强制转换错误。如果这是不可能的,关于我如何做到这一点的任何想法?

谢谢!

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define NI 5
#define DI 10
#define QU 25



bool isValid(int num) {
    return (num >= 10 && num <= 100 );
}

bool isMultiple(int num) {
        return (num % 5 == 0);
}


char *coinReturn(int insert) {

                                int dimes = insert/DI;
                                int remainder = insert % DI;
                                int nickels = remainder/NI;
                                int remainder2= nickels % NI;
                                char *m = ("Change returned. %d nickels and %d dimes\n",nickels, dimes);
                                return m;
}


int 
main (int argc, char *argv[])
{  for (int i = 1; i != argc; ++i) {
         int price = atoi(argv[i]);
        if (!isValid(price)) {
            printf("Price muse be from 10 cents to 100 cents.\n");
            break;
        } else if (!isMultiple(price)) {
                printf("Price must be a multiple of 5.\n");
                break;
        } else {
                printf(" Welcome to my Vending Machine!\n");
                printf("Pop is %d cents. Please enter nickels, dimes, or quarters\n", price);

                        int cents = 0;
                        char coin = '\0';

                        while (cents <= price && coin != 'E') {
                        printf(" PLease enter a coin [NDQR]\n");
                        scanf (" %c", &coin);

                        if (coin == 'N'|| coin == 'n') {
                                cents = cents + NI;
                                printf(" You have inserted 5 cents\n");
                        }
                        else if (coin == 'd' || coin == 'D') {
                                cents = cents + DI;
                                printf("You have inserted 10 cents\n");
                        }
                        else if (coin == 'Q' || coin == 'q') {
                                cents = cents + QU;
                                printf("You have entered 25 cents\n");
                        }
                        else if ( coin == 'R' || coin == 'r'){
                                printf("Change requested\n");
                                char *rtn2= coinReturn(cents);
                                printf("%s\n",rtn2 );
                        } else {
                                printf("Unknown coin. Rejected.\n");
                        }
                        int balance = price - cents;
                        printf("You have entered a total of %d cents\n", cents);

                        if (balance > 0) {
                        printf("You must enter %d more cents\n", balance);
                    } else {

                                char *rtn = coinReturn(cents);
                                printf("%s\n",rtn );
                         cents = 0;

                    }

                    }


               printf("DONE!\n");
                return 0;
}
}

【问题讨论】:

    标签: c string debugging return character


    【解决方案1】:

    这是行不通的:

    char *m = ("返回的更改。%d 个镍币和 %d 个硬币\n",nickels, dimes);

    也许摆脱 char * 并调用 printf?

    【讨论】:

    • 但我需要以某种方式返回该语句。我可以用 printf 做到这一点吗?
    • 不。您可以malloc 一个缓冲区,使用snprintf 对其进行格式化,然后将其返回。
    • 但是你对 return 所做的只是 printf 它。为什么不直接在函数中做 printf 呢?
    【解决方案2】:

    实际上可以按照您所说的进行。以下是您可能喜欢的两种解决方案:

    解决方案一:使用 printf 而不是返回。

    首先,您实际上并没有通过编写来格式化字符串

    char *m = ("Change returned. %d nickels and %d dimes\n", nickels, dimes);

    我们需要将这些值传递给一个函数来进行实际的格式化!

    其次,我不明白为什么我们需要从 coinReturn... 返回时我们可以简单地写

    printf("Change returned. %d nickels and %d dimes\n", nickels, dimes);

    我们完成了!

    但也许这不是我们想要的。也许我们想为这个函数返回一个字符串指针,我们也可以做到这一点:)

    解决方案 2:使用 snprintf 并返回指向静态缓冲区的指针

    char *coinReturn(int insert) {
        // set aside a buffer for our string.
        static char buf[512];
        int dimes = insert/DI;
        int remainder = insert % DI;
        int nickels = remainder/NI;
        int remainder2= nickels % NI;
        // output our string into the buffer.
        snprintf(buf, sizeof(buf),
            "Change returned. %d nickels and %d dimes\n", nickels, dimes);
        return buf;
    }
    

    首先我们留出一些内存来存储我们的格式化字符串,

    static char buf[512];

    请注意,必须将buf 声明为static,这样它才能在我们的coinReturn 函数的范围内继续存在。

    512 将是我们的最大字符串长度,在这里应该绰绰有余。

    让我们看看下一部分:

    snprintf(buf, sizeof(buf),
        "Change returned. %d nickels and %d dimes\n", nickels, dimes);
    

    (见:https://linux.die.net/man/3/printf

    第一个参数是我们的字符串将被写入的位置,buf

    第二个参数是snprintf 将写入的最大字节数(包括空终止符)。

    最后一个参数就像你已经熟悉的printf

    return buf;
    

    最后我们可以返回buf,知道结果将是一个指向我们格式化字符串的指针。


    在这两个解决方案中,第一个肯定更有意义 - 我看到 #2 存在很多问题(例如:它不是线程安全的),但如果这就是你想要的,它就可以完成工作在这里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多