c - 如何通过 C 中的函数操作字符串数组?

标签 c arrays string

我正在尝试编写代码,使用一个函数从 stdin 读取 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

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

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

“'%[^' 需要 'char *' 类型的参数,但参数 2 的类型为 'char (*)[101]'”

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

最佳答案

如果你不太热衷于使用 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]);

    }
}

关于c - 如何通过 C 中的函数操作字符串数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47121042/

相关文章:

改变数组的基址

java - 获取特定字符串后的下一个字符/字符串

检查输入字符串是否超过缓冲区限制(崩溃)

c - 与线程相关的错误文件描述符

c - 用于在引导加载程序应用程序中计算 crc 的软件逻辑

c - 为什么我的服务器只将文件的第一行写入客户端?

python - numpy randint 和 floor of rand 之间的区别

java - 如何从字符数组创建单词

string - 如何从 D 中的字节数组构造字符串

c - write vs fprintf - 为什么不同,哪个更好?