【问题标题】:How to manipulate array of strings via function in C?如何通过C中的函数操作字符串数组?
【发布时间】:2018-04-17 16:15:22
【问题描述】:

我正在尝试编写代码,使用函数从标准输入读取 42 个字符串,并且知道我保存了多少个字符串。 到目前为止,这是我想出的:

#define rows 42
#define chars 101

void populate(int* citiesCount, char cities[][chars]);

int main()
{
    char cities[rows][chars]; //array of strings to store all lines of txt file
    int citiesCount = 0; //how many lines there really are (may be less than 42)

    populate(&citiesCount, cities);

    //print all cities
    printf("NUMBER OF CITIES: %d\n", citiesCount);
    for(int i = 0; i < citiesCount; i++)
    {
        printf("CITY: %s\n", cities[i]);
    }
    printf("END\n");

    return 0;
}

void populate(int* citiesCount, char cities[][chars])
{
    char cntrl;
    for(int i = 0; i < rows; i++)
    {
        printf("%d\n", *citiesCount);
        scanf("%100[^\n]", &cities[*citiesCount++]); //read line of txt file and save it to array of strings
        printf("%s\n", cities[i]);
        cntrl = getchar(); //check, if I'm at end of file, if yes break loop
        if(cntrl == EOF)
            break;
    }
}

代码由以下语句编译

gcc -std=c99 -Wall -Wextra -Werror proj1.c -o proj1

在这个项目中,禁止使用动态内存分配。

如果我尝试编译代码,我会收到以下错误:

"'%[^' expects argument of type 'char *', but argument 2 has type 'char (*)[101]'"

我尝试了所有可能的方法来处理它,但找不到任何有效的方法。

【问题讨论】:

  • scanf("%100[^\n]", &amp;cities[*citiesCount++]); --> scanf("%100[^\n]", cities[(*citiesCount)++]);
  • 我删除了 & 符号,现在代码可以编译,但是在第一行之后它就崩溃了。
  • @xing *citiesCount++ 应该是 (*citiesCount)++
  • 将 *citiesCount++ 替换为 (*citiesCount)++ 后,代码运行良好。谢谢。
  • cntrl = getchar();这返回 int

标签: c arrays string


【解决方案1】:

如果你不太热衷于使用 scanf,这个应该会有所帮助

void populate(int* citiesCount, char cities[][chars])
{
    for(int i = 0; ( i < rows ) && fgets( cities[i], chars, stdin) ; i++)
    {
        // remove there if not required.
        printf("%d\n", (*citiesCount)++ );
        printf("%s\n", cities[i]);

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-25
    • 2020-09-04
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    相关资源
    最近更新 更多